The type 'System.Windows.Forms.GroupBox' cannot be used as type parameter 'T' in the generic type or method
my 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;
}
}
}
use :
private void btnCancel_Click(object sender, EventArgs e)
{
Global.TextBoxEmpty<GroupBox>(this.grpInfoBook);
}
error :
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'.
What is the correct code?
You don't really need the where
restriction at all since in the code you're using OfType
to filter the list anyways. However, if you want to keep the restriction, change it to reference 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;
}
}
}
Take a look at the docs for GroupBox
and you'll see it does not inherit from 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
The inheritance hierarchy of GroupBox is:
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.GroupBox
The type ContainerControl is not in this inheritance tree, hence the reason for the error message.
The generic constraint, you have defined restricts the usage to ContainerControl type. But GroupBox is not a containercontrol. It derives from Control class.
精彩评论