泛型Form||UserControl 即 :
BaseForm<T>:Form
根据泛型的定义:泛型是一种特殊的类型,它把指定类型的工作推迟到客户端代码声明并实例化类或方法的时候进行。
可以得到如果多个界面有相关关系,并且用到的Model继承自一个接口,或类,那再加上反射的话,可以节省大量代码.
- 创建一个类BaseForm继承自Form,创建泛型T,然后可以加上限制.UI包含了界面上的button,不要用Design.cs,不然编译不过去.
- 创建一个中间件,这是一个类继承自BaseForm,它也不能有.design.cs文件.一定要带一个空的构造函数,不然后面的几面无法进入界面设计器.
- 创建一个Form,它继承自StringMiddleware
- 如果想创建一个Int32类型的界面怎么办呢?跳转到第二步,第三不.Int32Form 和StringForm的一些通用方法可以在BaseForm里面进行编写.
- 运行结果:
-
-
the problem is that the designer is always creating an instance of the base class - direct parent in the inheritance hierarchy. I'm assuming that's because you are changing the definition of the class in design time.
So when you are designing MyEditorDialog, the designer actually has an instance of the System.Windows.Forms.Form class on which you add controls. But when you try to design MySubclassedDialog,the designer tries to create instance of the generic class MyEditorDialog<T> and fails. You get the same thing when you declare base form as abstract. The direct descendant can not be designed.
The only solution (that I know of) is to add a third concrete, non-generic class in between, which will give your descendant form capability to be designed. Really simple, though you get an extra class that has no other reason to exist.
public partial class MyEditorDialog <T> : Form where T: IMyInterface, new() { // ... } // this one can NOT be designed BUT allows design of the descendants public partial class MyNonGenericBaseDialog : MyEditorDialog<MyType> { public MyNonGenericBaseDialog() { } // ... } // this one can be designed since designer can create instance of MyNonGenericBaseDialog class public partial class MyDesignableSubclassedDialog : MyNonGenericBaseDialog { // ... }