[英]Instantiate a generic type knowing common base class
Im trying to accomplish something which may seem a bit convoluted but would be quite helpful in my situation, looks something like this. 我试图完成一些看起来有些令人费解但对我的情况会很有帮助的事情,看起来像这样。
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?
}
Because I can guarantee that all the constructors have the same signature I know this will work, just not sure how to let the compiler know. 因为我可以保证所有构造函数都具有相同的签名,所以我知道这是可行的,只是不确定如何让编译器知道。
Thanks in advance 提前致谢
I don't see any generics in here really, but it looks like you want: 我真的没有在这里看到任何泛型,但看起来像您想要的:
return (CommonBaseClass) Activator.CreateInstance(DataTypes[type]);
If you need to use parameterized constructors, use an alternative overload of Activator.CreateInstance
. 如果需要使用参数化的构造函数,请使用
Activator.CreateInstance
的替代重载。
Alternatively, consider changing your dictionary to be of delegates: 或者,考虑将您的词典更改为代表:
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]();
}
Try this: 尝试这个:
public class Foo
{
public static CommonBaseClass GetGenericObject<T>() where T : CommonBaseClass
{
return (CommonBaseClass)Activator.CreateInstance<T>();
}
public void Test()
{
CommonBaseClass b = GetGenericObject<Type1Object>();
}
}
Using generics can solve this problem a lot better than having a dictionary of type mapping. 使用泛型可以比使用类型映射字典更好地解决此问题。
A small test application: 小型测试应用程序:
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.