在变量的名称中传递按钮的编号

本文关键字:按钮 编号 变量 | 更新日期: 2023-09-27 18:07:55

我有这几行代码:

button0.BorderBrush = new SolidColorBrush(Colors.Red);
button1.BorderBrush = new SolidColorBrush(Colors.Red);
button2.BorderBrush = new SolidColorBrush(Colors.Red);
...

我怎样才能纠正这个错误:

(button + "numberOfButton").BorderBrush = new SolidColorBrush(Colors.Red);

在变量的名称中传递按钮的编号

任何时候你发现自己有这样的变量:

button0
button1
button2
etc...

应该是一个数组。如果控件本身在表单上已经是静态的,那么只需在加载表单时构建数组即可。像这样:

public class MyForm : Form
{
    private IEnumerable<Button> myButtons;
    public MyForm()
    {
        myButtons = new List<Button>
        {
            button0, button1, button2 // etc...
        };
    }
    // etc...
}

然后,当您需要遍历按钮时,只需遍历集合:

foreach (var button in myButtons)
    button.BorderBrush = new SolidColorBrush(Colors.Red);

如果需要通过索引引用集合元素,请使用IList<>而不是IEnumerable<>。如果需要做更复杂的事情,可以使用任意数量的集合类型。

您可以通过Control方法的名称找到它。发现:

var button = this.Control.Find("button0", true).FirstOrDefault();

但最好将按钮存储在数组中,并通过索引获取它们:

var buttons = new Control[10];
buttons[0] = button0;
...