【问题标题】:System.Windows.Forms.Control not contain "GetEnumerator" public definition?System.Windows.Forms.Control 不包含“GetEnumerator”公共定义?
【发布时间】:2013-11-30 21:39:18
【问题描述】:

当我想遍历 Forms 控件时,这个 foreach 语句 (foreach (Control __control in _control)) 会报错:

System.Windows.Forms.Control 不包含“GetEnumerator”公共 定义。所以foreach语句不能是 'System.Windows.Forms.Control' 类型变量。

这是我的代码:

public DataTable addFormControlName(DataTable dt, string[] controls)
        {
            foreach (string controlName in controls)
            {                
                foreach (Control _control in this.Controls)
                {
                    if (_control.Name.ToString() == controlName)
                    {
                        if (_control.HasChildren)
                        {
                            foreach (Control __control in _control)
                            {
                                //traverse the control like 'groupBox'...
                            }
                        }
                    }
                }                
            }
            return dt;
        }

我可以做些什么来避免这个问题?

【问题讨论】:

    标签: c# winforms foreach


    【解决方案1】:

    为了在foreach 循环中枚举一些(集合)对象,该对象应该实现IEnumerable 接口。 Control 不实现这个接口。因此你在这里有错误:

    foreach (Control __control in _control)
    

    如果您想枚举 _control 的子代,您应该枚举其 Controls 集合:

    foreach (Control __control in _control.Controls)
    

    还可以考虑使用 LINQ 按名称获取控件:

    var controlsToUse = Controls.Cast<Control>()
                                .Where(c => controls.Contains(c.Name));
    // do what you want
    

    【讨论】:

    • 我该怎么办?我实现了 IEnumerable?但在其他情况下我习惯这样做但没有错误。
    • 如果我错了,请纠正我,但它不需要一个名为GetEnumerator 的方法可以在不实现接口的情况下存在吗?
    • @DavidPilkington 是的,完全正确 - 你需要实现接口。简单的GetEnumerator 方法不会使您的对象可枚举
    猜你喜欢
    • 2023-03-16
    • 2014-07-10
    • 2014-04-24
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 2013-02-16
    • 2021-10-18
    • 2014-05-08
    相关资源
    最近更新 更多