C#泛型之Form(UserControl)


泛型Form||UserControl 即 :

BaseForm<T>:Form

根據泛型的定義:泛型是一種特殊的類型,它把指定類型的工作推遲到客戶端代碼聲明並實例化類或方法的時候進行。

可以得到如果多個界面有相關關系,並且用到的Model繼承自一個接口,或類,那再加上反射的話,可以節省大量代碼.

  1. 創建一個BaseForm繼承自Form,創建泛型T,然后可以加上限制.UI包含了界面上的button,不要用Design.cs,不然編譯不過去.

  2. 創建一個中間件,這是一個類繼承自BaseForm,它也不能有.design.cs文件.一定要帶一個空的構造函數,不然后面的幾面無法進入界面設計器.

  3. 創建一個Form,它繼承自StringMiddleware

  4. 如果想創建一個Int32類型的界面怎么辦呢?跳轉到第二步,第三不.Int32Form 和StringForm的一些通用方法可以在BaseForm里面進行編寫.
  5. 運行結果:

 

參考自:http://social.msdn.microsoft.com/Forums/en-US/winformsdesigner/thread/afdfce40-8d7a-4300-bd8d-26e18c320a71

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
    {
        // ... 
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM