开发者

Pass Type as a parameter to a function

开发者 https://www.devze.com 2023-02-06 22:51 出处:网络
I have a dictionary object Dictionary<string, Type> dict = ne开发者_运维百科w Dictionary<string, Type>();

I have a dictionary object

Dictionary<string, Type> dict = ne开发者_运维百科w Dictionary<string, Type>();

I also have a BaseClass and a number of child-classes, say: ChildClass1, ChildClass2, etc. The dictionary has values:

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"]);


you can invoke Activator.CreateInstance(type)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号