使用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.ControlTheref
在列表参数中是不需要的。顺便说一句,我想成为一个能够指定我要提取的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);