gpt4 book ai didi

c# - 使用 C# 从控件集合中递归获取控件集合

转载 作者:行者123 更新时间:2023-11-30 19:49:07 24 4
gpt4 key购买 nike

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

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'

有什么想法吗?

最佳答案

问题:

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

您不能将 Integer 转换为 Control

解决方案:

要解决此问题,请添加 where T : Controlwhere 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 关键字。由于 List 是引用类型,因此将传递它的引用。

关于c# - 使用 C# 从控件集合中递归获取控件集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4463319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com