简体   繁体   English

使用C#以递归方式从controlcollection中获取控件集合

[英]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? 有任何想法吗?

Problem: 问题:

Since T can be a reference type or a value type , compiler needs more information. 由于T可以是reference typevalue type ,因此编译器需要更多信息。

You can not convert and Integer to Control . 您无法转换和Integer Control

Solution: 解:

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 : Controlwhere T : class (更一般)约束,以声明T始终是引用类型。

Example: 例:

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);
    }
}
  • You also don't need ref keyword. 您也不需要ref关键字。 Since, List is a reference type, it's reference will be passed. 由于List是一个引用类型,它的引用将被传递。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM