使用C#从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);
}
}
我在使用以下行时遇到问题:
resultCollection.Add((T)control);
我收到错误...
Cannot convert type 'System.Web.UI.Control' to 'T'
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题:
由于
T
可以是引用类型
或值类型
,编译器需要更多信息。您无法将
Integer
转换为Control
。解决方案:
要解决此问题,请添加
where T : Control
或where T : class
(更通用的)约束声明T
始终是引用类型。示例:
ref
关键字。由于 List 是引用类型,因此将传递它的引用。Problem:
Since
T
can be areference type
or avalue type
, compiler needs more information.You can not convert and
Integer
toControl
.Solution:
To fix this, add
where T : Control
orwhere T : class
(a more general) constraint to state thatT
will always be a reference type.Example:
ref
keyword. Since, List is a reference type, it's reference will be passed.将其更改为
这将比您的 cod 更快,因为它不会调用
GetType()
。请注意,它还将添加继承
T
的控件。您还需要通过添加
where T : Control
来约束类型参数。Change it to
This will be faster than your cod, since it doesn't call
GetType()
.Note that it will also add controls that inherit
T
.You'll also need to constrain the type parameter by adding
where T : Control
.