C# 如何终止递归函数并返回值
我正在尝试使用递归函数在ASP.NET页面中查找TextBox控件。找到此控件后,我希望终止函数并返回它 我的主要问题是无法停止递归函数并返回控件 这是我的密码:C# 如何终止递归函数并返回值,c#,asp.net,C#,Asp.net,我正在尝试使用递归函数在ASP.NET页面中查找TextBox控件。找到此控件后,我希望终止函数并返回它 我的主要问题是无法停止递归函数并返回控件 这是我的密码: //execute recursive function to find a control in page by its id TextBox textbox = GetTextBoxByID(controlCollection, id); //recursive function private TextBox GetTextB
//execute recursive function to find a control in page by its id
TextBox textbox = GetTextBoxByID(controlCollection, id);
//recursive function
private TextBox GetTextBoxByID(ControlCollection controlCollection, string id)
{
foreach (Control control in controlCollection)
{
if (control is TextBox)
{
TextBox tb = (TextBox)control;
if (tb.ID == id)
{
//return selected texbox and terminate this recursion
return tb;
}
}
if (control.HasControls())
{
GetTextBoxByID(control.Controls, id);
}
}
//no control found return null
return null;
}
你又少了一张支票,就在这里:
if (control.HasControls())
{
var result = GetTextBoxByID(control.Controls, id);
if (result != null)
return result;
}
@ohmusama,是的,否则它不会通过所有可能的分支,而是在第一次
foreach
pass后终止,如果这返回更多元素的话。@walther,你就是那个人!它就像一个符咒:)谢谢你能解释一下你的例子吗?
private void button1_Click(object sender, EventArgs e)
{
Control ctrl = GetControlByName(this, "archHalfRoundWindowGroup");
}
public Control GetControlByName(Control Ctrl, string Name)
{
Control ctrl = new Control();
foreach (Control x in Ctrl.Controls)
{
if (x.Name == Name)
return ctrl=x;
if (x.Controls.Count > 0)
{
ctrl= GetControlByName(x, Name);
if (ctrl.Name != "")
return ctrl;
}
if (ctrl.Name != "")
return ctrl;
}
return ctrl;
}