Store class definition in dictionary, instance later

时间秒杀一切 提交于 2019-12-06 03:43:04

You can store type information with a Type object:

var dict = new Dictionary<String, Type>();

dict.Add("A", typeof(TextBox));
dict.Add("B", typeof(Button));

and create objects from it like this:

object a = Activator.CreateInstance(dict["A"]);

This will only work with types with a parameterless constructor. For instance, new TextBox(). If your types have constructors that take the same arguments, you can add the arguments after dict["A"] or pass an array.

I strongly recommend using a dependency injection library like Unity or Windsor Castle, but if you absolutely must, then you should do something like this:

Dictionary<string, System.Type> MyDict = new Dictionary<string, System.Type>();
MyDict.Add("A", typeof(MyAObjectClass));
MyDict.Add("B", typeof(MyBObjectClass));
MyDict.Add("C", typeof(MyCObjectClass));

string typeIwant = "B";
var myobject = Activator.CreateInstance(MyDict[typeIwant]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!