简体   繁体   English

将类型作为参数传递给函数

[英]Pass Type as a parameter to a function

I have a dictionary object 我有一个字典对象

Dictionary<string, Type> dict = new Dictionary<string, Type>();

I also have a BaseClass and a number of child-classes, say: ChildClass1 , ChildClass2 , etc. The dictionary has values: 我也有一个BaseClass和许多子类,例如: ChildClass1ChildClass2等。字典具有以下值:

dict.Add("type1", typeof(ChildClass1));
dict.Add("type2", typeof(ChildClass2));

My question is - is there any way to do something like this: 我的问题是-有没有办法做这样的事情:

BaseClass c = new <<get a type from the dict: dict[type1]>>()?

I just want to make my solution more flexible, but I'm not sure if that's possible at all. 我只是想使我的解决方案更加灵活,但是我不确定是否完全可能。 Thanks! 谢谢!

var c = (BaseClass)Activator.CreateInstance(dict["type1"]);

您可以调用Activator.CreateInstance(type)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM