[英]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.