既然子控件表现为一个树形结构,为什么我不用递归去遍历子控件?当我看着不太优雅的嵌套循环代码时,我突然这样想到。使用递归,根本不用关心所需的控件在哪一层,而且代码简洁。
下面就是两种遍历方式:
1、循环方式:
for (int i =0; i<GlobalCategoryPanel.Controls.Count;i++)//GlobalCategoryPanel是个Panel控件
{
if(GlobalCategoryPanel.Controls[i] is AdvancedPanel)//AdvancedPanel是个自定义控件
{
AdvancedPanel ap=(AdvancedPanel)GlobalCategoryPanel.Controls[i];
for(int ap_i=0;ap_i<ap.Controls.Count;ap_i++)
{
if(ap.Controls[ap_i] is Panel)
{
Panel ap_panel=(Panel)ap.Controls[ap_i];
for(int ap_panel_i=0;ap_panel_i<ap_panel.Controls.Count;ap_panel_i++)
{
if(ap_panel.Controls[ap_panel_i] is RadioButtonList)
{
RadioButtonList rbl=(RadioButtonList)ap_panel.Controls[ap_panel_i];
al.Add(int.Parse(rbl.SelectedValue));
}
}
}
}
}
}
{
if(GlobalCategoryPanel.Controls[i] is AdvancedPanel)//AdvancedPanel是个自定义控件
{
AdvancedPanel ap=(AdvancedPanel)GlobalCategoryPanel.Controls[i];
for(int ap_i=0;ap_i<ap.Controls.Count;ap_i++)
{
if(ap.Controls[ap_i] is Panel)
{
Panel ap_panel=(Panel)ap.Controls[ap_i];
for(int ap_panel_i=0;ap_panel_i<ap_panel.Controls.Count;ap_panel_i++)
{
if(ap_panel.Controls[ap_panel_i] is RadioButtonList)
{
RadioButtonList rbl=(RadioButtonList)ap_panel.Controls[ap_panel_i];
al.Add(int.Parse(rbl.SelectedValue));
}
}
}
}
}
}
2、递归方式
private void Button1_Click(object sender, System.EventArgs e)
{
FindSelecedControl(GlobalCategoryPanel);
}
private void FindSelecedControl(Control control)//递归函数
{
if(control is RadioButtonList)
{
RadioButtonList rbl=(RadioButtonList)control;
al.Add(int.Parse(rbl.SelectedValue));
}
else
{
for(int i=0;i<control.Controls.Count;i++)
{
FindSelecedControl(control.Controls[i]);
}
}
}
{
FindSelecedControl(GlobalCategoryPanel);
}
private void FindSelecedControl(Control control)//递归函数
{
if(control is RadioButtonList)
{
RadioButtonList rbl=(RadioButtonList)control;
al.Add(int.Parse(rbl.SelectedValue));
}
else
{
for(int i=0;i<control.Controls.Count;i++)
{
FindSelecedControl(control.Controls[i]);
}
}
}
要是早想到用递归的方式,昨天我也就不用那么迟睡觉了。
以后在编程中一定要多考虑是否有更好的方法,不能只顾埋头写代码,要从多个角度考虑解决问题的方法。