Check implementation of recursive interface, C #

I have a situation in WebForm where I need to reload the control tree to find all the controls that implement this interface.

How can I do it?

I tried writing an extension method like this

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;
    }
}

But this does not like the cast to Ton line 7. I also thought about trying the as operator, but this does not work with interfaces.

I saw the Scott Hanselmans investigation , but I couldn’t extract anything useful from it.

Can anyone give me any directions. Thanks.

Greg

+3
source share
3 answers

I think you need to break this method into 2 parts

  • , , # 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;
        }
    }
}

, , OfType

var all = someControl.FindAllControls().OfType<ISomeInterface>();
+10

as.

public static class ControlExtensions {
    public static List<T> FindControlsByInterface<T>(this Control control) where T : class
    {
        List<T> retval = new List<T>();
        T item = control as T;
        if (T != null)
            retval.Add(item);

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

        return retval;
    }
}
+2

Is casting really necessary? If you have control that implements T, this should not be. Also, take a look at the is keyword:

if (control is T)   
        retval.Add(control);
+1
source

Source: https://habr.com/ru/post/1713166/


All Articles