简体   繁体   中英

How to pass object[] to Activator.CreateInstance(type, params object[])

I have a class which contains an empty constructor and one that accepts an array of objects as its only parameter. Something like...

public myClass(){ return; }
public myClass(object[] aObj){ return; }

This is the CreateInstance() method call that I use

object[] objectArray = new object[5];

// Populate objectArray variable
Activator.CreateInstance(typeof(myClass), objectArray);

it throws System.MissingMethodException with an added message that reads "Constructor on type 'myClass' not found"

The bit of research that I have done has always shown the method as being called

Activator.CreateInstance(typeof(myClass), arg1, arg2);

Where arg1 and arg2 are types (string, int, bool) and not generic objects. How would I call this method with only the array of objects as its parameter list?

Note: I have tried adding another variable to the method signature. Something like...

public myClass(object[] aObj, bool notUsed){ return; }

and with this the code executed fine. I have also seen methods using reflection which were appropriate but I am particularly interested in this specific case. Why is this exception raised if the method signature does in fact match the passed parameters?

把它投射到object

Activator.CreateInstance(yourType, (object) yourArray);

Let's say you have constructor:

class YourType {
   public YourType(int[] numbers) {
      ...
   }
}

I believe you would activate like so by nesting your array, the intended parameter, as a item of the params array:

int[] yourArray = new int[] { 1, 2, 4 };
Activator.CreateInstance(typeof(YourType ), new object[] { yourArray });

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