【问题标题】:The type 'System.Windows.Forms.GroupBox' cannot be used as type parameter 'T' in the generic type or method类型“System.Windows.Forms.GroupBox”不能用作泛型类型或方法中的类型参数“T”
【发布时间】:2011-08-24 04:44:33
【问题描述】:

我的班级:

public static class Global
{
    public static void TextBoxEmpty<T>(T ContainerControl) where T : ContainerControl
    {
        foreach (var t in ContainerControl.Controls.OfType<TextBox>())
        {
            t.Text = string.Empty; 
        }
    }
}

使用:

private void btnCancel_Click(object sender, EventArgs e)
{
    Global.TextBoxEmpty<GroupBox>(this.grpInfoBook);
}

错误:

类型“System.Windows.Forms.GroupBox”不能用作类型 泛型类型或方法中的参数“T” 'Global.TextBoxEmpty(T)'。没有隐式引用转换 从“System.Windows.Forms.GroupBox”到 'System.Windows.Forms.ContainerControl'。

什么是正确的代码?

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    您根本不需要where 限制,因为在代码中您使用OfType 来过滤列表。但是,如果您想保留限制,请将其更改为引用System.Windows.Controls.Control

    public static class Global
    {
        public static void TextBoxEmpty<T>(T ContainerControl) where T : Control
        {
            foreach (var t in ContainerControl.Controls.OfType<TextBox>())
            {
                t.Text = string.Empty; 
            }
        }
    }
    

    查看GroupBox 的文档,您会发现它不是从ContainerControl 继承的:

    System.Object
      System.Windows.Threading.DispatcherObject
        System.Windows.DependencyObject
          System.Windows.Media.Visual
            System.Windows.UIElement
              System.Windows.FrameworkElement
                System.Windows.Controls.Control
                  System.Windows.Controls.ContentControl
                    System.Windows.Controls.HeaderedContentControl
                      System.Windows.Controls.GroupBox
    

    http://msdn.microsoft.com/en-us/library/system.windows.controls.groupbox.aspx

    【讨论】:

      【解决方案2】:

      GroupBox的继承层次是:

        System.Object 
          System.MarshalByRefObject
            System.ComponentModel.Component
              System.Windows.Forms.Control
                System.Windows.Forms.GroupBox
      

      ContainerControl 类型不在此继承树中,因此是错误消息的原因。

      【讨论】:

        【解决方案3】:

        您定义的通用约束将使用限制为 ContainerControl 类型。但是 GroupBox 不是一个容器控件。它派生自 Control 类。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多