My first generic casting (C #)

I was very excited when writing this general function when the compiler threw an error ( unable to cast T to System.Web.UI.Control)

I basically pass it a type when I call it, and it searches for all the controls for that type. An error occurs whenl.Add((T)ctrl);

    private List<T> RecurseTypes<T>(Control ctrls)
    {
        var l = new List<T>();
        foreach (var ctrl in ctrls.Controls)
            if (ctrl.GetType() is T)
                l.Add((T)ctrl);
        return l;
    }

Am I missing something or am I just out of luck?

+5
source share
5 answers
private List<T> RecurseTypes<T>(Control parent) where T: Control
{
    var l = new List<T>();
    foreach (var child in parent.Controls)
        if (child is T)
            l.Add((T)child);
    return l;
}

2 changes:

  • add where T : Controlgeneral restriction
  • see usage is(control may be T, but GetType()returns Type, which is never Control)

Also, note that this is really not recursive; it could be simple:

return ctrl.Controls.OfType<T>().ToList();
+13
source

.NET 3.5 , OfType<T>() Cast<T>() , .

OfType<T>() , , Cast<T>() , , , .

+2

?

:

private List<T> RecurseTypes<T>(Control ctrl)
    {
        List<T> l = new List<T>();
        foreach (var ctrls in ctrl.Controls)
        {
            if (ctrls is T)
                l.Add((T)ctrls);
        }
        return l;
    }
0

.

private List<T> RecurseTypes<T>(Control ctrls) where T : System.Web.UI.Control
0

, T .

, , Control T, T ??? Control.

:

private List<T> RecurseTypes<T>(Control ctrls) where T : Control

, , T. , Control:

 if (ctrl.GetType().IsSubclassOf(typeof(Control))

, , T.

0

All Articles