简体   繁体   English

Activator.CreateInstance(...)未找到参数化构造函数

[英]Activator.CreateInstance(…) is not finding parameterized constructor

Given the following sample code; 给出以下示例代码;

class Program
{
    static void Main(string[] args)
    {
        var results = GetChildren().ToList();
    }

    static IEnumerable<MyBaseClass> GetChildren()
    {
        return Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(t => t.BaseType == typeof(MyBaseClass))
            .Select(o => (MyBaseClass)Activator.CreateInstance(o, null));
    }
}

abstract class MyBaseClass
{ }

class MyChildClass : MyBaseClass
{
    public MyChildClass(object paramOne)
    {

    }
}

I'm receiving the following error; 我收到以下错误;

MissingMethodException: Constructor on type 'CreateInstanceCtorIssue.MyChildClass' not found. MissingMethodException:找不到类型“CreateInstanceCtorIssue.MyChildClass”的构造函数。

However, if I add a parameterless constructor, it creates the objects OK. 但是,如果我添加一个无参数构造函数,它会创建对象OK。

I'm trying to work out why the parameter I'm suppying to CreateInstance is not causing it to find the correct constructor. 我试图弄清楚为什么我要为CreateInstance提供的参数不会导致它找到正确的构造函数。 Anyone got any ideas? 有人有任何想法吗?

Basically, the second argument of the method you are calling is a params array . 基本上, 您调用方法的第二个参数是params数组 What's happening is that the C# compiler is treating your method-call as though you are passing this argument in using the "unexpanded" form, ie by passing a null array-reference. 发生的事情是C#编译器正在处理你的方法调用,好像你是在使用“未扩展”形式传递这个参数,即传递一个null数组引用。 On the other hand, your intent is to use the "expanded" form, ie pass a reference to an array containing a single null-reference. 另一方面,您的意图是使用“展开”形式,即将引用传递给包含单个空引用的数组。

You can coax the compiler to do what you want like this: 你可以哄骗编译器做你想做的事情:

// Unexpanded:
Activator.CreateInstance(o, new object[] { null })

// Expanded explictly:
Activator.CreateInstance(o, (object) null )

You have to pass the constructor parameters: 你必须传递构造函数参数:

.Select(o => (MyBaseClass)Activator.CreateInstance(o, new object[] { someParam }));

MyChildClass expects a single parameter of type object for its constructor - you have to pass this parameter within an array. MyChildClass需要一个类型为object的参数作为其构造函数 - 您必须在数组中传递此参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM