[譯]Visual Basic 2005在語言上的增強(九)部分類型

部分類型允許在不同的源文件中定義同一個類型。在其中一個文件中可以使用普通方式進行的類型定義(作者說的“普通”的意思是不需要使用Partial關鍵字,涕淌注):
Public Class TestPartial
    '代碼實現……
End Class

而在其他的源文件中,你必須使用Partial關鍵字來告訴編譯器,這其中的代碼是對原始類定義的一個擴展:
Partial Public Class TestPartial
    '代碼實現……
End Class

類中由IDE生成的代碼被標以Partial關鍵字,並且和用戶填寫的代碼分離開來。你在工程中添加一個名爲TestForm的窗體,來看看生成的源文件。你可能很驚訝是吧,因爲除了窗體類聲明的空框架之外就空空如也了。從前那些“Windows窗體自動生成的代碼”區域裏那些設計器生成的代碼到哪兒去了呢?

現在,設計器生成的代碼都被存放在TestForm.Designer.vb文件中,你可以點擊解決方案瀏覽器工具條上的Show All Files按鍵來閱讀這個文件。你不應該修改這個文件中的代碼(實際上你是可以修改的,只是不推薦你這麼做,涕淌注),但是,如果你想在設計器文件被再次生成時保留下一些東西,你可以把需要的代碼複製粘貼到TestForm.vb文件中。

工程小組可以利用部分類的優點,爲每一個開發人員分配編寫同一個類的某一個部分類文件的任務。多人開發已經不再需要對同一個源文件進行共享訪問了,因爲你們現在可以把同一個類的定義分散到多個源文件中。


@以下是原文供網友們參考@

Partial Types

Partial types allow definition of a single type across multiple source files. The type definition has a normal declaration in one file:
Public Class TestPartial
    'implemention...
End Class

In other source files, you use the Partial keyword to tell the compiler that this code is a continuation of the original class definition:
Partial Public Class TestPartial
    'implemention...
End Class

Code in classes generated by designers in the IDE is marked with the Partial keyword, and is separated from user code. Add a form named TestForm to a project and look at the resulting source file. You may be surprised to see that it's empty except for the form's class declaration. Where's all the designer-generated code that used to go inside the Windows Form Designer Generated Code region?

The designer-generated code is now placed in file TestForm.designer.vb, which you can see by clicking the Show All Files button in the Solution Explorer toolbar. You shouldn't change the code in this file, but you can copy and paste what you need into the TestForm.vb file if you want to preserve something when the designer file is later regenerated.

Project teams can take advantage of partial classes by giving each developer a file containing their portion of the class. Multiple developers no longer need to share access to the same source files since you can now separate a class definition into multiple source files.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章