Instantiating a constructor with parameters in an internal class with reflection

后端 未结 4 1852
后悔当初
后悔当初 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:50

    (tested successfully)

    object instantiatedType =
       Activator.CreateInstance(typeToInstantiate,
       System.Reflection.BindingFlags.NonPublic |
         System.Reflection.BindingFlags.Instance,
       null, new object[] {parameter}, null);
    

    There are two issues this addresses:

    • the new object[] {parameter} helps it handle the issue of passing an object[] as a single parameter of method that takes a params object[] argument
    • the BindingFlags helps resolve the non-public constructor

    (the two nulls relate to the binder; the default binder behaviour is fine for what we want)

提交回复
热议问题