在字典中存储类定义,稍后实例 [英] Store class definition in dictionary, instance later
问题描述
我想做的是类似以下内容(所有对象类都有一个通用界面):
What I want to do is something like the following (All object class have a common interface):
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]();
我如何编程这样的东西?
How could I program something like this?
这样做的目的是不必创建我将在我的字典中存储的每一种类型的实例(可能是相当多的一个),而只是实际使用的实例。
The purpose of this is to not have to create instances of every single type I will store in my dictionary (could be quite a bit of them) and instead only instance the one I'm actually going to use.
推荐答案
您可以使用Type对象存储类型信息:
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));
并从中创建对象:
object a = Activator.CreateInstance(dict["A"]);
这只适用于带无参数构造函数的类型。例如, new TextBox()
。如果您的类型具有相同参数的构造函数,则可以在 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.
这篇关于在字典中存储类定义,稍后实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!