c#以递归方式检查接口的实现,c#

Gre*_*g B 3 c# reflection recursion interface

我在WebForm中有一种情况,我需要在控制树中执行,以找到实现给定接口的所有控件.

我该怎么做?

我试过写这样的扩展方法

public static class ControlExtensions
{
    public static List<T> FindControlsByInterface<T>(this Control control)
    {
        List<T> retval = new List<T>();
        if (control.GetType() == typeof(T))                
            retval.Add((T)control);


        foreach (Control c in control.Controls)
        {
            retval.AddRange(c.FindControlsByInterface<T>());
        }

        return retval;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是它不喜欢第T7行的强制转换.我也考虑过尝试使用as运算符,但这不适用于接口.

我看到了斯科特汉塞尔曼斯的耻辱,但却无法收集任何有用的信息.

任何人都可以给我任何指示.谢谢.

格雷格

Jar*_*Par 10

我认为你需要将这个方法分成两部分

  1. 递归查找控件
  2. 查找控件实现基于#1的接口

这是#1

public static IEnumerable<Control> FindAllControls(this Control control) {
    yield return control;
    foreach ( var child in control.Controls ) {
        foreach ( var all in child.FindAllControls() ) {
          yield return all;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在要获取类型的所有控件,请使用OfType扩展方法

var all = someControl.FindAllControls().OfType<ISomeInterface>();
Run Code Online (Sandbox Code Playgroud)