类型'System.Windows.Forms.GroupBox'不能在泛型类型或方法中用作类型参数'T'

时间:2011-08-24 04:44:33

标签: c# generics

我的班级:

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'。

什么是正确的代码?

3 个答案:

答案 0 :(得分:4)

您根本不需要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

答案 1 :(得分:0)

GroupBox的继承层次结构是:

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

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

答案 2 :(得分:0)

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

相关问题