【发布时间】:2012-03-21 04:11:48
【问题描述】:
我正在尝试为System.Web.UI.Control 编写一个扩展方法,它将在其ControlCollection 中搜索特定Type 的实例,并返回找到的第一个实例。深度优先很简单,但是我想先搜索广度,以便更高的集合优先。
我当前的方法有缺陷,会提前退出,在整个搜索未完成的某些情况下返回 null。我希望我接近正确的解决方案,但需要一些新的眼光。有什么建议吗?
public static T FindFirstControlOfType<T>(this Control rootControl, bool searchRecursively) where T : Control
{
// list for container controls
List<Control> controlsWithChildren = new List<Control>();
// iterate the current control collection first
foreach (Control child in rootControl.Controls)
{
if (child.GetType().IsAssignableFrom(typeof(T)))
{
return (T)child;
}
// track those controls containing children
if (child.HasControls())
{
controlsWithChildren.Add(child);
}
}
// if recursion is enabled, search the child nodes
if (searchRecursively)
{
foreach (Control control in controlsWithChildren)
{
return FindFirstControlOfType<T>(control, true);
}
}
// if never found, return null
return null;
}
编辑 - 基于标记答案的工作解决方案,适用于任何感兴趣的人:
public static T FindFirstControlOfType<T>(this Control rootControl, bool searchNestedControls) where T : Control
{
Queue<Control> queue = new Queue<Control>();
EnqueueChildControls(queue, rootControl);
while (queue.Count > 0)
{
Control current = queue.Dequeue();
if (current.GetType() == typeof(T))
{
return (T)current;
}
if (searchNestedControls)
{
EnqueueChildControls(queue, current);
}
}
return null;
}
private static void EnqueueChildControls(Queue<Control> queue, Control control)
{
foreach (Control current in control.Controls)
{
queue.Enqueue(current);
}
}
【问题讨论】:
标签: c# asp.net recursion queue breadth-first-search