您可以将所有控件添加到数组中,然后遍历数组:
private readonly Control[] m_Controls;
public MyControl() {
InitializeComponent();
m_Controls = new[] {
AName1, AName2, AName3,
BName1, BName2, BName3,
}
}
private void DoStuff(string text) {
foreach (Control c in m_Controls) {
c.Text = text;
}
}
或者,如果您真的不想拥有硬编码列表,并且控件都是您运行代码的控件的一部分,则可以使用 Controls 集合:
private void DoStuff(string text) {
for (int i=0; i<4; i++) {
this.Controls["AName" + i].Text = text;
}
}
但是,如果表单上有很多控件,这会很慢,因为它会线性扫描表单上的每个控件,直到找到具有指定名称的控件。
编辑:对于多个 repititions,您可以使用嵌套循环:
for (string prefix in new[] { "A", "B", "C", ...}) {
for (int i=0; i<4; i++) {
this.Controls[prefix + "Name" + i].Text = text;
}
}