使用C#以递归方式从controlcollection中获取控件集合
目前,我正在尝试从递归控件集合(转发器)中提取动态创建的控件(复选框和下拉列表)的集合。 这是我正在使用的代码。
private void GetControlList(ControlCollection controlCollection, ref List resultCollection) { foreach (Control control in controlCollection) { if (control.GetType() == typeof(T)) resultCollection.Add((T)control); if (control.HasControls()) GetControlList(controlCollection, ref resultCollection); } }
我遇到以下问题:
resultCollection.Add((T)control);
我收到错误……
Cannot convert type 'System.Web.UI.Control' to 'T'
有任何想法吗?
问题:
由于T
可以是reference type
或value type
,因此编译器需要更多信息。
您无法转换和Integer
Control
。
解:
要解决此问题,请添加where T : Control
或where T : class
(更一般)约束,以声明T
始终是引用类型。
例:
private void GetControlList(ControlCollection controlCollection, ref List 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); } }
- 您也不需要
ref
关键字。 由于List是一个引用类型,它的引用将被传递。
将其更改为
var c = control as T; if (c != null) resultCollection.Add(c);
这将比你的鳕鱼快,因为它不会调用GetType()
。
请注意,它还将添加inheritanceT
控件。
您还需要通过添加where T : Control
来限制类型参数。