【问题标题】:Recursive function to find user controls in a generic type在泛型类型中查找用户控件的递归函数
【发布时间】:2016-12-12 06:41:10
【问题描述】:

这是我的代码

    private void FindControls<T>(Control control, List<T> list)
    {
        foreach (Control c in control.Controls)
        {
            if (c != null)
            {
                if (c is T)
                {
                    list.Add(c);  //<-- Problem is here
                }
                else
                {
                    FindControls<T>(c, list);
                }
            }
        }
    }

我收到了消息

"最好的重载匹配 'System.Collection.Generic.List.Add(T)' 有一些无效参数"

这是另一种查找特定控件的方法

    private void MyMethod(Employee e)
    {
        List<MyUserControlType> employees = new List<MyUserControlType>();
        this.FindControls<MyUserControlType>(this.MyControlRoot, employees);
        foreach (var employee in employees)
        {
            ....
        }
    }

我想返回不继承自 Control 类型的 MyUserControlType 类型的控件列表。从 UserControl 继承

我该如何解决这个问题?

【问题讨论】:

  • 你必须将 C 转换为 T。

标签: c# list generics recursion


【解决方案1】:

你可以使用 as 运算符来转换它

            if (c is T)
            {
                list.Add((c as T));  //<-- Problem is here
            }

可以通过修改方法定义来放置该约束

private void FindControls<T>(Control control, List<T> list) where T : class
{

(OR) 正如@Ivan 在评论中指出的那样,您可以使用强制转换运算符直接对其进行强制转换,这不需要您在方法中放置通用约束

            if (c is T)
            {
                list.Add((T)c);  //<-- Problem is here
            }

【讨论】:

  • 我已经尝试过了,但我得到:“类型参数 'T' 不能与 'as' 运算符一起使用,因为它没有类类型约束也没有 'class' 约束”跨度>
  • 为什么as T而不是(T)?
  • @IvanStoev,有道理,但由于它处于if(c is T) 条件下,使用as 投射它不会有问题..
  • 我知道它是安全的:) 我只是好奇你为什么一开始就选择那个,这反过来又要求你添加约束。而另一个可以在没有约束的情况下工作。
  • @IvanStoev,嗯,这就是发布答案时想到的,但是很好,谢谢。包括那个。
猜你喜欢
  • 2016-05-28
  • 1970-01-01
  • 2020-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2020-02-13
  • 2012-07-03
相关资源
最近更新 更多