[英]Instantiate a generic type knowing common base class
我試圖完成一些看起來有些令人費解但對我的情況會很有幫助的事情,看起來像這樣。
public class CommonBaseClass {}
public class Type1Object : CommonBaseClass {}
public class Type2Object : CommonBaseClass {}
public class Type3Object : CommonBaseClass {}
public static Dictionary<string, Type> DataTypes = new Dictionary<string, Type>()
{
{ "type1" , typeof(Type1Object) },
{ "type2" , typeof(Type2Object) },
{ "type3" , typeof(Type3Object) }
};
public static CommonBaseClass GetGenericObject(string type)
{
return new DataTypes[type](); //How to instantiate generic class?
}
因為我可以保證所有構造函數都具有相同的簽名,所以我知道這是可行的,只是不確定如何讓編譯器知道。
提前致謝
我真的沒有在這里看到任何泛型,但看起來像您想要的:
return (CommonBaseClass) Activator.CreateInstance(DataTypes[type]);
如果需要使用參數化的構造函數,請使用Activator.CreateInstance
的替代重載。
或者,考慮將您的詞典更改為代表:
private static Dictionary<string, Func<CommonBaseClass>> DataTypes =
new Dictionary<string, Func<CommonBaseClass>>
{
{ "type1", () => new Type1Object() }
{ "type2", () => new Type2Object() },
{ "type3", () => new Type3Object() }
};
public static CommonBaseClass GetGenericObject(string type)
{
return DataTypes[type]();
}
嘗試這個:
public class Foo
{
public static CommonBaseClass GetGenericObject<T>() where T : CommonBaseClass
{
return (CommonBaseClass)Activator.CreateInstance<T>();
}
public void Test()
{
CommonBaseClass b = GetGenericObject<Type1Object>();
}
}
使用泛型可以比使用類型映射字典更好地解決此問題。
小型測試應用程序:
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var dataTypes = new Dictionary<string, Type>
{
{"type1", typeof (Type1Object)},
{"type2", typeof (Type2Object)},
{"type3", typeof (Type3Object)}
};
Func<string, CommonBaseClass> GetGenericObject = t =>
{
return (CommonBaseClass)Activator.CreateInstance(dataTypes[t]);
};
var myGenericObject = GetGenericObject("type1");
}
}
public class CommonBaseClass { }
public class Type1Object : CommonBaseClass { }
public class Type2Object : CommonBaseClass { }
public class Type3Object : CommonBaseClass { }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.