C# Activator.CreateInstance(string) 和 Activator.CreateInstance<T>() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/57439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 10:13:33  来源:igfitidea点击:

Activator.CreateInstance(string) and Activator.CreateInstance<T>() difference

提问by juan

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).

我有一个工厂模式,其中包含几个带有内部构造函数的类(如果不是通过工厂,我不希望它们被实例化)。

My problem is that CreateInstancefails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter.

我的问题是,CreateInstance除非我在非公共参数上传递“true”,否则会因“没有为此对象定义无参数构造函数”错误而失败。

Example

例子

// 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).

但是,我无法找到如何传递“true”参数以使其接受非公共构造函数(内部)。

Did I miss something or it isn't possible?

我错过了什么还是不可能?

采纳答案by Kilhoffer

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.

您的工厂方法仍然是泛型的,但对激活器的调用将不会使用泛型重载。但是您仍然应该获得相同的结果。

回答by rpetrich

If you absolutely require that the constructor be private you can try something like this:

如果你绝对要求构造函数是私有的,你可以尝试这样的事情:

public abstract class GenericFactory<T> where T : MyAbstractType
{
    public static T GetInstance()
    {
        return (T)Activator.CreateInstance(typeof(T), true);
    }
}

Otherwise you're best off adding the new constraint and going that route:

否则,您最好添加新约束并走这条路线:

public abstract class GenericFactory<T> where T : MyAbstractType, new()
{
    public static T GetInstance()
    {
        return new T;
    }
}

You're trying to use GenericFactory as a base class for all of your factories rather than writing each from scratch right?

您正在尝试使用 GenericFactory 作为所有工厂的基类,而不是从头开始编写每个工厂,对吗?

回答by mpastern

besides Activator.CreateInstance(typeof(T), true) to work, T should have default constructor

除了 Activator.CreateInstance(typeof(T), true) 工作,T 应该有默认构造函数