动态创建C#类的实例

时间:2016-01-10 03:36:44

标签: c# .net

我想动态创建类的实例,因此我创建了该类对象的字典,并通过将计数器附加到字符串来指定名称。但是如何访问对象的属性?

代码是这样的:

int count = 0;
string name = "MyInstanceName" + count.ToString();

Dictionary<string, MyClass> d = new Dictionary<string, MyClass>();
d.Add(name, new MyClass(Parameter));

//try to retrieve the Property - this doesn't work
textBox1.Text = d[name.Property];

3 个答案:

答案 0 :(得分:7)

你可以这样做

int count = 0;
string name = "MyInstanceName" + count.ToString();

var d = new Dictionary<string, MyClass>();
d.Add(name, new MyClass());

textBox1.Text = d[name].Property;

您创建了一个Dictionary,其密钥为string,其值为MyClass的实例。

使用Dictionary索引时,括号[]之间的值应该是键,在本例中是一个字符串。

myDictionary["keyValue"]

答案 1 :(得分:0)

textBox1.Text = d[name].Property;

答案 2 :(得分:0)

除了Alberto Monteiro的答案之外,别忘了投射你的物体:

textBox1.Text = (myClass) d["MyInstanceName1"].Property;

var myInstanceX = d["MyInstanceName1"].Property;
textBox1.Text = myInstanceX.myStringProperty();

在C#中(与VB不同),如果编译器可以在其他地方确定变量,则不需要指定变量的类型,因此您也可以简化:

Dictionary<string, MyClass> d = new Dictionary<string, MyClass>();

进入

var d = new Dictionary<string, MyClass>();

var是一个类型化的变量声明符(与javascript不同)