2010-01-23 174 views
1

有没有办法像这样在C#中更改对象的属性。C#动态更改对象的属性

int Number = 1;

label [Number] .Text =“Test”;

并且结果会将label1.Text更改为“Test”;

希望你明白我的意思。

回答

4

你可以把所有的标签到一个数组:

var labels = new[] { label1, label2, label3, label4 }; 

然后使用数组索引:

int number = 0; 
labels[number].Text = "Test"; 
+0

请记住,在C#数组索引从0 – 2010-01-23 11:16:39

3

标签添加到列表

List<Label> list = new List<Label>() 
list.Add(label1); 
list.Add(label2); 

list[0].Text = "Text for label 1"; 
list[1].Text = "Text for label 2"; 

Reflection是另一方式,但很可能这不是你的意思。

0

也许字典(或关联数组)可以帮助你。其中,key是整数和价值 - 标签:

var dictionary = new Dictionary<int, Label>(); 
dictionary[2] = label1; 
dictionary[7] = label2; 
dictionary[12] = label2; 

int number = 2; 
dictionary[number].Text = "Test";