简体   繁体   中英

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.

However, if I add a parameterless constructor, it creates the objects OK.

I'm trying to work out why the parameter I'm suppying to CreateInstance is not causing it to find the correct constructor. Anyone got any ideas?

Basically, the second argument of the method you are calling is a params array . 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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