获取T类型的所有控件的通用方法

时间:2012-08-23 01:02:08

标签: c# asp.net generics

我有一个返回List<T>子控件的方法,如下所示:

void GetAllControlsOfType<T>(List<T> lst, Control parent) where T:class
{
    if (parent.GetType() == typeof(T))
        lst.Add(parent as T);

    foreach (Control ch in parent.Controls)
        this.GetAllControlsOfType<T>(lst, ch);
}

但我必须像这样使用它:

List<WebControl> foo = new List<WebControl>();
GetAllControlsOfType<WebControl>(foo, this); //this = webpage instance

肯定有一些c#魔术可以让我编写一个我可以这样调用的方法:

List<WebControl> foo = GetAllControlsOfType<WebControl>(this);

1 个答案:

答案 0 :(得分:2)

“魔术”只是声明另一种返回List<T>而不是void的方法。

List<T> GetAllControlsOfType<T>(Control parent) where T : class {
    List<T> list = new List<T>();
    GetAllControlsoFType<T>(list, parent);   // Invoke your existing method
    return list;
}

因为您正在使用递归,所以您不能简单地修改现有方法以返回List<T>,因为这样做会使您无法跟踪该列表和建立在它上面。

其他一些小问题:

  • 你有:

    if (parent.GetType() == typeof(T))
    

    但将其写成:

    会更清楚
    if (parent is T)
    

    当然,当你使用T的子类时,你真的希望你的方法失败

  • 您可能需要考虑将parent声明为this Control parent(假设它在静态类中声明),将新方法声明为扩展方法

    这将允许您以this.GetAllControlsOfType<WebControl>()

  • 的形式调用该方法