Windows窗体通用inheritance

我有这些课程:

class Foo : Form where T1, T2 : EventArgs class MiddleGoo : Foo class Goo : MiddleGoo 

X,Y只是从EventArgs派生的简单类。

我在设计师中看到Goo,但我想在Foo和Goo之间创建一个类Boo,如下所示:

 class Boo : Foo where T1 : EventArgs class MiddleGoo : Boo class Goo : MiddleGoo 

中产阶级的解决方法不起作用,任何想法?

编辑:我的意思是Y和X是像YEventArgs和XEventArgs这样的类,我的问题是当我将Y定义为T2但仍希望通过T1保持通用时,在设计器类Boo中查看。

EDIT2:我刚刚意识到我拼错了Y级的东西……

 public class Foo : Form where T1 : EventArgs where T2 : EventArgs { } public class Boo : Foo where T1 : EventArgs { } public class MiddleGoo : Boo { } class Goo : MiddleGoo { } public class MyEventArgs2 : EventArgs { } public class MyEventArgs1 : EventArgs { } 

并且要清楚我在Designer中看不到Boo …(我也看不到MiddleGoo但我不需要)

对于Visual Studio版本> = VS2015.1

VS2015.1开始,Windows窗体设计器显示具有通用基本classe的类,没有任何问题。 因此,对于较新版本的VS,不再需要其他post中的解决方法,并且以下类将在设计器中显示而没有任何问题。

所以有这样的基类generics类:

 public class BaseForm : Form { public TModel Model {get;set;} public TService Service {get; set;} } 

您可以在设计器中创建派生表单而不会出现任何问题:

 public class FooForm: BaseForm { } 

较旧版本的Visual Studio

在旧版本的Visual Studio中,当设计人员想要在设计器中托管您的表单时,它会尝试创建表单基类的实例,并且您的类必须具有非通用基础,以便设计人员可以显示它。

所以你可以看到BaseForm:Form可以在设计器中显示但是CategoryForm:BaseForm无法在设计器中显示。 作为这些情况下的解决方法,您应该创建一个BaseCategoryForm:BaseForm ,然后在设计器中显示CategoryForm:BaseCategoryForm

假设这是您的基类,它接受TModel作为Model和TService作为Service,例如:

 public class BaseForm : Form { public TModel Model {get;set;} public TService Service {get; set;} } 

然后用这行代码创建一个中间forms:

 Public Class BaseFooForm: BaseForm{ } 

最终forms如下:

 public class FooForm: BaseFooForm { } 

现在最后的FooForm有设计师,你可以正常使用它。 这样,您可以创建要在设计器中支持的类。

注意

此更新也适用于控件设计器。 因此,在WinForm UserControl的通用基类中,您不再需要VS> = VS2015.1此类解决方法。

Foo类中的T2 Type参数需要可转换为EventArgs 。 但是当你定义你的Boo类时,你没有包含那个约束。 将您的Boo类更改为:

 class Boo : Foo where T1 : EventArgs where Y : EventArgs 

此外,您在Foo类声明中遇到语法错误。 将其更改为:

 class Foo where T1 : EventArgs where T2 : EventArgs