【问题标题】:Activator.CreateInstance(string) and Activator.CreateInstance<T>() differenceActivator.CreateInstance(string) 和 Activator.CreateInstance<T>() 的区别
【发布时间】: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


【解决方案1】:

要解决这个问题,你不能像这样改变你的用法吗:

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

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

【讨论】:

  • 如果不存在重载,我就不得不说不。
【解决方案2】:

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

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 作为所有工厂的基类,而不是从头开始编写每个工厂,对吗?

【讨论】:

  • 第一个选项和Kilhoffer的一样第二个不行,在需要类型有公共参数的where中加new(),这正是我不想要的
  • 是的,他的帖子出现在我打字的时候。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多