gpt4 book ai didi

c# - 在其他地方创建的通用类

转载 作者:太空宇宙 更新时间:2023-11-03 13:24:49 24 4
gpt4 key购买 nike

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

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

我得到了异常(exception):

An unhandled exception of type 'System.MissingMethodException' occurred in mscorlib.dll

Additional information: Constructor on type 'System.String' not found.

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

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

我得到下一个异常:

An unhandled exception of type 'System.MissingMethodException' occurred in mscorlib.dll

Additional information: No parameterless constructor defined for this object.

你能告诉我哪里出了问题吗?我该如何改进?

最佳答案

问题是这一行:

object o = Activator.CreateInstance(GenSinType);

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

您可能想要做的是,代替该行,调用泛型类型的静态方法。参见 this question举个例子。

通常,您要求可以从其名称的字符串表示形式而不是从实际的类型对象中获取类型的实例,这会让您的生活变得非常困难。除非真的有必要,否则您应该尽量不要这样做。

关于c# - 在其他地方创建的通用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22743008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com