Skip to main content
 首页 » 编程设计

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

2024年02月23日13thcjp

我的类(class):

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); 
} 

错误:

The type 'System.Windows.Forms.GroupBox' cannot be used as type parameter 'T' in the generic type or method 'Global.TextBoxEmpty(T)'. There is no implicit reference conversion from 'System.Windows.Forms.GroupBox' to 'System.Windows.Forms.ContainerControl'.

正确的代码是什么?

请您参考如下方法:

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