【发布时间】:2012-02-02 22:59:32
【问题描述】:
我正在尝试按名称获取控件。我写了以下代码:
public Control GetControlByName(string name)
{
Control currentControl;
for(int i = 0,count = Controls.Count; i < count; i++)
{
currentControl = Controls[i];
if (currentControl.HasChildren)
{
while (currentControl.HasChildren)
{
for(int x = 0,size = currentControl.Controls.Count; x < size; x++)
{
currentControl = currentControl.Controls[x];
if (currentControl.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return currentControl;
}
}
}
}
else
{
if (currentControl.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return currentControl;
}
}
}
return null;
}
它只返回空值。有人可以指出我的错误吗?欢迎任何帮助或改进此代码的方法。
【问题讨论】:
-
currentControl = currentControl.Controls[x];在循环中看起来很可疑
-
你为什么不使用递归?