繁体   English   中英

在其他地方创建的通用类

[英]Generic classes to create in other places

我有自己的(简单的,没有线程安全性)通用单例类,如下所示:

public class GenericSingleton<T> where T : class
{
    private static T uniqueInstance = null;
    private GenericSingleton() { }

    public static T getInstance()
    {
        if (uniqueInstance == null)
        {
            Type t = typeof(T);
            uniqueInstance = (T)Activator.CreateInstance(t);

        }
        return uniqueInstance;
    }

}

在其他类中,我想创建我的通用类:

public class GenericFactory
{
    public object CreateObject(string TypeName, bool IsSingleton, params object[] Parameters)
    {
        if (IsSingleton)
        {
            Type genericType = typeof(GenericSingleton<>);
            Type typeArgs =  Type.GetType(TypeName);
            Type GenSinType = genericType.MakeGenericType(typeArgs);
            object o = Activator.CreateInstance(GenSinType);
            return o;
        }
        else
        {
            return Activator.CreateInstance(Type.GetType(TypeName), Parameters);
        }

    }

如果我使用它,它正在工作

 GenericFactory gf = new GenericFactory();
    List<int> w = (List<int>)gf.CreateObject("System.Collections.Generic.List`1[System.Int32]", false, new int[] { 10, 22 });
            Console.WriteLine(w[1]+w[0]);
            Console.WriteLine(w.GetType());

不幸的是,如果我这样做

object test = gf.CreateObject("System.String", true, 7);

我受到鼓舞:

mscorlib.dll中发生了'System.MissingMethodException'类型的未处理异常

附加信息:找不到类型'System.String'的构造方法。

此外,如果我用它来创建通用单例,例如:

List<int> ww = (List<int>)gf.CreateObject("System.Collections.Generic.List`1[System.Int32]", true, new int[] { 10, 22 });

我得到下一个例外:

mscorlib.dll中发生了'System.MissingMethodException'类型的未处理异常

附加信息:没有为此对象定义无参数构造函数。

您能告诉我什么地方出了问题,如何改善呢?

问题是这一行:

object o = Activator.CreateInstance(GenSinType);

您正在尝试创建单例类的实例,但是单例模式的全部要点是您不能从类本身之外进行操作。 您将构造函数设为私有,因此Activator无法访问它

您可能想要做的是代替该行,在您的泛型类型上调用静态方法。 有关示例,请参见此问题

通常,通过要求您可以从名称的字符串表示形式而不是实际的类型对象中获取类型的实例,使自己的生活非常困难。 除非真的很重要,否则您应该尽量不要这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM