Instantiating a constructor with parameters in an internal class with reflection

后端 未结 4 1851
后悔当初
后悔当初 2020-11-27 18:10

I have something along the lines of this:

object[] parameter = new object[1];
parameter[0] = x;
object instantiatedType =
Activator.CreateInstance(typeToInst         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 18:57

    The issue is that Activator.CreateInstance(Type, object[]) does not consider non-public constructors.

    Exceptions

    MissingMethodException: No matching public constructor was found.

    This is easily shown by changing the constructor to publicvisibility; the code then works correctly.

    Here's one workaround (tested):

     BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
     CultureInfo culture = null; // use InvariantCulture or other if you prefer
     object instantiatedType =   
       Activator.CreateInstance(typeToInstantiate, flags, null, parameter, culture);
    

    If you only require the parameterless constructor this will work as well:

    //using the overload: public static object CreateInstance(Type type, bool nonPublic)
    object instantiatedType = Activator.CreateInstance(typeToInstantiate, true)
    

提交回复
热议问题