2011-08-24 54 views
1

我的類別:類型 'System.Windows.Forms.GroupBox' 不能在通用類型或方法被用作類型參數 'T'

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'的隱式引用轉換 。

什麼是正確的代碼?

回答

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

+0

謝謝你Samuel Neff – mrJack

0

分組框中的繼承層次結構是:

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

ContainerControl類型不在此繼承樹中,因此是錯誤消息的原因。

0

您定義的通用約束將使用限制爲ContainerControl類型。但GroupBox不是一個容器控件。它來自Control類。

相關問題