你可以添加所有的控件數組,然後通過數組迭代:
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;
}
}
或者,如果你真的不希望有一個硬編碼的列表,以及控件的所有部分你在運行代碼控制,你可以使用控件集合:
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;
}
}
通常你不應該使用被改寫的名字找到能夠控制這種方式 - 你生成代碼這些控件?如果是這樣,你應該將它們保存在例如列表或併發包 –