【发布时间】:2008-09-11 19:42:33
【问题描述】:
不,这不是关于泛型的问题。
我有一个工厂模式,其中包含多个具有内部构造函数的类(如果不通过工厂,我不希望它们被实例化)。
我的问题是CreateInstance 失败并出现“没有为此对象定义无参数构造函数”错误,除非我在非公共参数上传递“true”。
例子
// Fails
Activator.CreateInstance(type);
// Works
Activator.CreateInstance(type, true);
我想让工厂通用以使其更简单,如下所示:
public class GenericFactory<T> where T : MyAbstractType
{
public static T GetInstance()
{
return Activator.CreateInstance<T>();
}
}
但是,我无法找到如何传递“true”参数以使其接受非公共构造函数(内部)。
是我错过了什么还是不可能?
【问题讨论】:
-
为什么不定义一个将私有布尔变量设置为 true 的无参数构造函数?
标签: c# generics design-patterns