Using C# to recursively get a collection of controls from a controlcollection

后端 未结 2 1147
滥情空心
滥情空心 2020-12-12 00:25

Currently I am trying to extract a collection of dynamically created controls (checkboxes and dropdownlists) from a recursive control collection (repeater). This is the cod

相关标签:
2条回答
  • 2020-12-12 01:15

    Change it to

    var c = control as T;
    if (c != null)
        resultCollection.Add(c);
    

    This will be faster than your cod, since it doesn't call GetType().
    Note that it will also add controls that inherit T.

    You'll also need to constrain the type parameter by adding where T : Control.

    0 讨论(0)
  • 2020-12-12 01:16

    Problem:

    Since T can be a reference type or a value type, compiler needs more information.

    You can not convert and Integer to Control.

    Solution:

    To fix this, add where T : Control or where T : class (a more general) constraint to state that T will always be a reference type.

    Example:

    private void GetControlList<T>(ControlCollection controlCollection, ref List<T> resultCollection)
    where T : Control
    {
        foreach (Control control in controlCollection)
        {
            //if (control.GetType() == typeof(T))
            if (control is T) // This is cleaner
                resultCollection.Add((T)control);
    
            if (control.HasControls())
                GetControlList(control.Controls, ref resultCollection);
        }
    }
    
    • You also don't need ref keyword. Since, List is a reference type, it's reference will be passed.
    0 讨论(0)
提交回复
热议问题