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

时间:2020-03-05 18:51:45  来源:igfitidea点击:

不,这不是关于泛型的问题。

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

我的问题是,除非我在非公共参数上传递" true",否则" CreateInstance"将失败,并显示"没有为此对象定义无参数构造函数"错误。

例子

// 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"参数以使其接受非公共构造函数(内部)。

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

解决方案

回答

为了解决这个问题,我们不能这样改变用法:

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

工厂方法仍然是通用的,但是对激活器的调用将不使用通用重载。但是我们仍然应该达到相同的结果。

回答

如果我们绝对要求构造函数是私有的,则可以尝试如下操作:

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

否则,最好是添加新约束并遵循以下路线:

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

我们试图将GenericFactory用作所有工厂的基类,而不是从头开始编写每个工厂,对吗?

回答

除了可以使用Activator.CreateInstance(typeof(T),true)之外,T还应具有默认构造函数