Windows Forms Generic Inheritance

前端 未结 2 1495
遇见更好的自我
遇见更好的自我 2020-12-21 00:55

I have these classes:

class Foo : Form 
    where T1, T2 : EventArgs

class MiddleGoo : Foo

class Goo : MiddleGoo

相关标签:
2条回答
  • 2020-12-21 01:13

    For Visual Studio Version >= VS2015.1

    Starting from VS2015.1, Windows Forms Designer shows classes which have generic base classe without any problem. So the workaround which is in other posts is no more required for newer versions of VS and the following class will be shown in designer without any problem.

    So having a base generic class like this:

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

    You can create the derived form without any problem in designer:

    public class FooForm: BaseForm<Foo,FooService> 
    {
    }
    

    Older Versions of Visual Studio

    In older versions of Visual Studio, when the designer wants to host your form in designer, it tries to create an instance of base class of your form, and your class must have a non-generic base to so the designer can show it.

    So you can see BaseForm<T>:Form can be shown in designer but CategoryForm:BaseForm<Category> can not be shown in designer. As a workaround in these cases you should create a BaseCategoryForm:BaseForm<Category> and then CategoryForm:BaseCategoryForm will be shown in designer.

    Example

    Suppose this is your base class that accepts TModel as Model and TService as Service for example:

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

    Then create an intermediate form this way, with this line of code:

    Public Class BaseFooForm: BaseForm<Foo, FooService>{ }
    

    And the final form this way:

    public class FooForm: BaseFooForm
    {
    }
    

    Now the final FooForm has designer and you can work with it normally. This way you can create your classes to be supported in designer.

    Note

    The update is also applied on control designer. So also in generic base class for WinForm UserControl you no more need such workaround for VS>=VS2015.1 .

    0 讨论(0)
  • 2020-12-21 01:16

    The T2 Type parameter in Foo class needs to be convertible to EventArgs. But when you are defining your Boo class, you aren't including that constraint. Change your Boo class to this:

    class Boo<T1, Y> : Foo<T1, Y>
        where T1 : EventArgs
        where Y : EventArgs
    

    Also, you have got a syntax error at the Foo class declaration. Change it to :

    class Foo<T1, T2>
        where T1 : EventArgs
        where T2 : EventArgs
    
    0 讨论(0)
提交回复
热议问题