C# 类型“System.Windows.Forms.GroupBox”不能用作泛型类型或方法中的类型参数“T”

C# 类型“System.Windows.Forms.GroupBox”不能用作泛型类型或方法中的类型参数“T”,c#,generics,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.Em

我的班级:

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; 
        }
    }
}
使用:

错误:

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

正确的代码是什么?

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

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


GroupBox的继承层次结构是:

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

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

GroupBox的继承层次结构是:

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

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

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

您定义的泛型约束将使用限制为ContainerControl类型。但是GroupBox不是一个容器控件。它源于控制类

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
  System.Object 
    System.MarshalByRefObject
      System.ComponentModel.Component
        System.Windows.Forms.Control
          System.Windows.Forms.GroupBox