Activator.CreateInstance(字符串)和Activator.CreateInstance< T>()的区别 [英] Activator.CreateInstance(string) and Activator.CreateInstance<T>() difference
问题描述
没有,这不是一个关于仿制药的问题。
No, this is not a question about generics.
我有几类内部构造工厂模式(我不希望他们被实例化如果不是通过工厂)。
I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory).
我的问题是,的CreateInstance
失败,出现此对象定义无参数的构造函数错误,除非我通过对非公有制参数真。
My problem is that CreateInstance
fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter.
示例
// Fails
Activator.CreateInstance(type);
// Works
Activator.CreateInstance(type, true);
我想使工厂通用,使之成为简单一点,就像这样:
I wanted to make the factory generic to make it a little simpler, like this:
public class GenericFactory<T> where T : MyAbstractType
{
public static T GetInstance()
{
return Activator.CreateInstance<T>();
}
}
不过,我无法找到如何传递真参数为它接受非公共构造函数(内部)。
However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal).
我错过了什么,或者是不可能的?
Did I miss something or it isn't possible?
推荐答案
要解决这个问题,想不出你只是改变你的用法,例如:
To get around this, couldnt you just alter your usage as such:
public class GenericFactory<T> where T : MyAbstractType
{
public static T GetInstance()
{
return Activator.CreateInstance(typeof(T), true);
}
}
您的工厂方法仍然是通用的,但电话对激活不会使用一般超载。但你仍然要达到相同的结果。
Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results.
这篇关于Activator.CreateInstance(字符串)和Activator.CreateInstance< T>()的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!