Chr*_*CTX 3 c# dictionary lazy-loading
我想要做的是如下所示(所有对象类都有一个共同的接口):
MyDict.Add("A", MyAObjectClass); // Not an instance
MyDict.Add("B", MyBObjectClass);
MyDict.Add("C", MyCOjbectClass);
String typeIwant = "B"; // Could be passed to a function or something
MyCommonInterface myobject = MyDict[typeIwant]();
Run Code Online (Sandbox Code Playgroud)
我怎么能编写这样的东西?
这样做的目的是不必创建我将存储在我的字典中的每种类型的实例(可能是相当多的),而只是实例我实际将要使用的实例.
您可以使用Type对象存储类型信息:
var dict = new Dictionary<String, Type>();
dict.Add("A", typeof(TextBox));
dict.Add("B", typeof(Button));
Run Code Online (Sandbox Code Playgroud)
并从中创建对象,如下所示:
object a = Activator.CreateInstance(dict["A"]);
Run Code Online (Sandbox Code Playgroud)
这仅适用于具有无参数构造函数的类型.例如,new TextBox().如果类型具有采用相同参数的构造函数,则可以在dict["A"]数组之后添加参数或传递数组.