How to instantiate an object with a private constructor in C#?

后端 未结 4 433
盖世英雄少女心
盖世英雄少女心 2020-12-03 09:41

I definitely remember seeing somewhere an example of doing so using reflection or something. It was something that had to do with SqlParameterCollection which i

4条回答
  •  没有蜡笔的小新
    2020-12-03 10:27

    // the types of the constructor parameters, in order
    // use an empty Type[] array if the constructor takes no parameters
    Type[] paramTypes = new Type[] { typeof(string), typeof(int) };
    
    // the values of the constructor parameters, in order
    // use an empty object[] array if the constructor takes no parameters
    object[] paramValues = new object[] { "test", 42 };
    
    TheTypeYouWantToInstantiate instance =
        Construct(paramTypes, paramValues);
    
    // ...
    
    public static T Construct(Type[] paramTypes, object[] paramValues)
    {
        Type t = typeof(T);
    
        ConstructorInfo ci = t.GetConstructor(
            BindingFlags.Instance | BindingFlags.NonPublic,
            null, paramTypes, null);
    
        return (T)ci.Invoke(paramValues);
    }
    

提交回复
热议问题