在循环中按名称操作多个对象

时间:2016-04-08 07:41:17

标签: c# .net loops object

如何在循环中操作多个对象。例如,您有30个按钮,并希望更改其背景颜色。它们被称为button1,button2等。

for (int i=1; i<31; i++)
{
    button+i.BACKGROUND.COLOR = AWESOME.BACKGROUND.COLOR;
}

那么&#34;按钮+ i的正确语法是什么。&#34;或者有更有效的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以将所有按钮放在列表中然后使用foreach吗?

List<Button> buttons = new List<Button>();
//at some point, in a constructor or Loaded event add all the buttons that have been created to the list
foreach(var button in buttons)
{
}

理论上你可以通过反射获取按钮并将它们添加到列表中,在某些时候你知道按钮将存在:

var t = this.GetType();

var fields = t.GetFields(BindingFlags.NonPublic |
                     BindingFlags.Instance);
//assuming you are doing this in a xaml.cs, if not you may need to change
// the above to GetProperties or use Public flag, depending on how your buttons
// are defined.
foreach (var f in fields)
{
    if (f.FieldType == typeof (Button))
        _buttons.Add(f.GetValue(this));

}