Noob Issue with Activate.CreateInstance



我正在努力能够在运行时动态调用类的实例化。

我花了今天早上的大部分时间在谷歌上搜索答案,但我在这个世界上很绿色,所以我确信答案是有意义的,但它们对我来说不是。

public class MSD : IGBRule
{
public MSD(GoverningBodyRulesGet_Result GBRule, int UserID)
{}

线路错误和错误都在下面

object v = Activator.CreateInstance(Type.GetType("RulesEngine.Rules.MSD, RulesEngine.Rules"), UserID, GBRules);

System.MissingMethodException:"找不到类型'RulesEngine.Rules.MSD'上的构造函数。

如果要创建一个对象并将参数传递给构造函数,则必须以正确的顺序提供参数,与在构造函数中指定的顺序匹配。因此,在您的情况下,您希望在用户 id 之前传递规则:

var type = Type.GetType("RulesEngine.Rules.MSD, RulesEngine.Rules");
object v = Activator.CreateInstance(type, GBRules, UserID);

如果将构造函数参数直接传递给CreateInstance方法,则必须小心使用常见类型,因为可能会意外选择未调用正确构造函数的不同重载。您可以通过传递带有要传递的参数的对象数组来避免这种情况:

var type = Type.GetType("RulesEngine.Rules.MSD, RulesEngine.Rules");
object[] args = new object[] { GBRules, UserID };
object v = Activator.CreateInstance(type, args);

最新更新