使用C#以递归方式从controlcollection中获取控件集合

And*_*ans 2 c# asp.net controlcollection

目前我正在尝试从递归控件集合(转发器)中提取动态创建的控件(复选框和下拉列表)的集合.这是我正在使用的代码.

private void GetControlList<T>(ControlCollection controlCollection, ref List<T> resultCollection)
{
    foreach (Control control in controlCollection)
    {
        if (control.GetType() == typeof(T))
            resultCollection.Add((T)control);

        if (control.HasControls())
            GetControlList(controlCollection, ref resultCollection);
    }
}
Run Code Online (Sandbox Code Playgroud)

我遇到以下问题:

resultCollection.Add((T)control);
Run Code Online (Sandbox Code Playgroud)

我收到了错误......

Cannot convert type 'System.Web.UI.Control' to 'T'
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

dec*_*one 5

问题:

既然T可以是a reference type或a value type,编译器需要更多信息.

您不能转换和IntegerControl.

解:

要解决此问题,请添加where T : Controlwhere T : class(更常规)约束状态,该状态T始终为引用类型.

例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 您也不需要ref关键字.由于List是一个引用类型,它的引用将被传递.