如何实例化一个对象,在C#中的私有构造? [英] How to instantiate an object with a private constructor in C#?
本文介绍了如何实例化一个对象,在C#中的私有构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我肯定记得看到某处这样使用反射或某事的例子。这是一些曾与SqlParameterCollection这不是由用户可创建做(如果我没有记错的话)。遗憾的是再也不能找到它。
任何人都可以在这里分享这一招?不,我认为这是发展一种有效的方法,我只是在做这个的可能性非常感兴趣。
解决方案
//类型构造函数的参数,以
//使用空类型[]数组,如果构造函数没有参数
类型[] paramTypes =新类型[ ] {typeof运算(字符串)的typeof(INT)};
//构造函数参数的值,以
//如果构造函数没有参数
对象[] = paramValues新的对象[使用空对象[]数组] {测试,42};
TheTypeYouWantToInstantiate例如=
构建物LT; TheTypeYouWantToInstantiate>(paramTypes,paramValues);
// ...
公共静态牛逼构建< T>(键入[] paramTypes,对象[] paramValues)
{
键入t = typeof运算(T);
ConstructorInfo CI = t.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic可,
空,paramTypes,NULL);
回报率(T)ci.Invoke(paramValues);
}
I definitely remember seeing somewhere an example of doing so using reflection or something. It was something that had to do with SqlParameterCollection which is not creatable by a user (if I'm not mistaken). Unfortunately cannot find it any longer.
Can anyone please share this trick here? Not that I consider it a valid approach in development, I'm just very interested in the possibility of doing this.
解决方案
// 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<TheTypeYouWantToInstantiate>(paramTypes, paramValues);
// ...
public static T Construct<T>(Type[] paramTypes, object[] paramValues)
{
Type t = typeof(T);
ConstructorInfo ci = t.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null, paramTypes, null);
return (T)ci.Invoke(paramValues);
}
这篇关于如何实例化一个对象,在C#中的私有构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文