我试图完成一些看起来有点复杂但对我的情况很有帮助的事情,看起来像这样。
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]();
}
关于c# - 实例化一个知道公共(public)基类的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11161709/