Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C#从controlcollection递归获取控件集合_C#_Asp.net_Controlcollection - Fatal编程技术网

使用C#从controlcollection递归获取控件集合

使用C#从controlcollection递归获取控件集合,c#,asp.net,controlcollection,C#,Asp.net,Controlcollection,目前,我正在尝试从递归控件集合(中继器)中提取动态创建的控件集合(复选框和下拉列表)。这是我正在使用的代码 private void GetControlList<T>(ControlCollection controlCollection, ref List<T> resultCollection) { foreach (Control control in controlCollection) { if (control.GetType

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

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);
    }
}
我得到了错误

Cannot convert type 'System.Web.UI.Control' to 'T'
有什么想法吗?

问题: 由于
T
可以是
引用类型
值类型
,编译器需要更多信息

您不能将和
整数
转换为
控件

解决方案: 要解决此问题,请添加
其中的T:Control
其中的T:class
(更一般的)约束,以声明
T
将始终是引用类型

例子:
private void GetControlList(ControlCollection ControlCollection,ref List resultCollection)
其中T:控制
{
foreach(controlCollection中的控件)
{
//if(control.GetType()==typeof(T))
if(控件为T)//这更干净
结果收集。添加((T)对照组);
if(control.HasControls())
GetControlList(control.Controls,ref resultCollection);
}
}
  • 您也不需要
    ref
    关键字。由于列表是引用类型,因此将传递它的引用
将其更改为

var c = control as T;
if (c != null)
    resultCollection.Add(c);
这将比cod更快,因为它不调用
GetType()

请注意,它还将添加继承
T
的控件


您还需要通过添加
来约束类型参数,其中T:Control

您真的需要泛型吗?所有控件都派生自System.Web.UI.ControlThe
ref
在列表参数中是不需要的。顺便说一句,我想成为一个能够指定我要提取的Web控件的人。@MadHur,他想做我假设的
GetControlList(…)
之类的事情。你还需要在最后一行代码中使用controlCollection.controls。否则,您将处于一个通过原始控件集合递归的无止境循环中;
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);
    }
}
var c = control as T;
if (c != null)
    resultCollection.Add(c);