[英]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)'.
类型'System.Windows.Forms.GroupBox'不能在泛型类型或方法'Global.TextBoxEmpty(T)'中用作类型参数'T'。 There is no implicit reference conversion from 'System.Windows.Forms.GroupBox' to 'System.Windows.Forms.ContainerControl'.
没有从'System.Windows.Forms.GroupBox'到'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. 您根本不需要
where
限制,因为在您使用OfType
的代码中无论如何都要过滤列表。 However, if you want to keep the restriction, change it to reference System.Windows.Controls.Control
: 但是,如果要保留限制,请将其更改为引用
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
: 看看
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 http://msdn.microsoft.com/en-us/library/system.windows.controls.groupbox.aspx
The inheritance hierarchy of GroupBox is: GroupBox的继承层次结构是:
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. ContainerControl类型不在此继承树中,因此出现错误消息的原因。
The generic constraint, you have defined restricts the usage to ContainerControl type. 您定义的泛型约束将使用限制为ContainerControl类型。 But GroupBox is not a containercontrol.
但是GroupBox不是容器控件。 It derives from Control class.
它派生自Control类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.