[英]Pass Type as a parameter to a function
我有一个字典对象
Dictionary<string, Type> dict = new Dictionary<string, Type>();
我也有一个BaseClass和许多子类,例如: ChildClass1 , ChildClass2等。字典具有以下值:
dict.Add("type1", typeof(ChildClass1));
dict.Add("type2", typeof(ChildClass2));
我的问题是-有没有办法做这样的事情:
BaseClass c = new <<get a type from the dict: dict[type1]>>()?
我只是想使我的解决方案更加灵活,但是我不确定是否完全可能。 谢谢!
var c = (BaseClass)Activator.CreateInstance(dict["type1"]);
您可以调用Activator.CreateInstance(type)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.