[英]Using C# to recursively get a collection of controls from a controlcollection
Currently I am trying to extract a collection of dynamically created controls (checkboxes and dropdownlists) from a recursive control collection (repeater). 目前我正在尝试从递归控件集合(转发器)中提取动态创建的控件(复选框和下拉列表)的集合。 This is the code I am using.
这是我正在使用的代码。
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);
}
}
I am having problems with the following line: 我遇到以下问题:
resultCollection.Add((T)control);
I get the error ... 我收到了错误......
Cannot convert type 'System.Web.UI.Control' to 'T'
Any ideas? 有任何想法吗?
Since T
can be a reference type
or a value type
, compiler needs more information. 由于
T
可以是reference type
或value type
,因此编译器需要更多信息。
You can not convert and Integer
to Control
. 您无法转换和
Integer
Control
。
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. 要解决此问题,请添加
where T : Control
或where 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);
}
}
ref
keyword. ref
关键字。 Since, List is a reference type, it's reference will be passed. 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()
. 这将比你的鳕鱼快,因为它不会调用
GetType()
。
Note that it will also add controls that inherit T
. 请注意,它还将添加继承
T
控件。
You'll also need to constrain the type parameter by adding where T : Control
. 您还需要通过添加
where T : Control
来限制类型参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.