博文主要以下圖中的控件來比較這兩種方式獲取控件的方式:
1. 最簡單的方式:
private void GetControls1(Control fatherControl)
{
Control.ControlCollection sonControls = fatherControl.Controls;
//遍歷所有控件
foreach (Control control in sonControls)
{
listBox1.Items.Add(control.Name);
}
}
結果:
獲取的結果顯示在右側的ListBox中,可以發現沒有獲取到Panel、GroupBox、TabControl等控件中的子控件。
2. 在原有方式上增加遞歸:
private void GetControls1(Control fatherControl)
{
Control.ControlCollection sonControls = fatherControl.Controls;
//遍歷所有控件
foreach (Control control in sonControls)
{
listBox1.Items.Add(control.Name);
if (control.Controls != null)
{
GetControls1(control);
}
}
}
結果:
絕大多數控件都被獲取到了,但是仍然有兩個控件Timer、ContextMenuStrip沒有被獲取到。
3. 使用反射(Reflection):
private void GetControls2(Control fatherControl)
{
//反射
System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
for (int i = 0; i < fieldInfo.Length; i++)
{
listBox1.Items.Add(fieldInfo[i].Name);
}
}
結果:
結果顯示所有控件都被獲取到了。