【问题标题】:Manipulating multiple objects by their name in a loop在循环中按名称操作多个对象
【发布时间】:2016-04-08 07:41:16
【问题描述】:

如何在一个循环中操作多个对象。例如,您有 30 个按钮并且想要更改它们的背景颜色。它们被称为button1、button2等等。

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

那么“button+i”的正确语法是什么?还是有更有效的方法来做到这一点?

【问题讨论】:

  • 将它们放入Collection,然后使用Collection
  • 为什么不为此创建一个数组或按钮列表?
  • WPF?表格?网络表单? MVC? ...?
  • 使用索引的 C# 语法是使用 [],因此如果您循环遍历 Button[],请使用 button[i].BACKGROUND.COLOR = ... 访问它们
  • 你是什么意思“他们被称为button1,button2等等。”?按钮存储在哪里,名称存储在哪里?

标签: c# .net loops object


【解决方案1】:

你能把所有的按钮放在一个列表中然后使用 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));

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多