Partial classes in C#
Def: The partial keyword allows the class, struct, method or interface to span across multiple files.
Desc and Ex: Typically, a class will reside entirely in a single file. However, in situations where multiple developers need access to the same class, or more likely in the situation where a code generator of some type is generating part of a class, then having the class in multiple files can be beneficial.
The way that the partial keyword is used is to simply place partial before class, struct, or interface. In the following example, the class TheBigClass resides in two separate source files, BigClassPart1.cs and BigClassPart2.cs ://BigClassPart1.cs partial class TheBigClass{
public void MethodOne(){}}//BigClassPart2.cs partial class TheBigClass{public void MethodTwo(){}}
When the project that these two source files are part of is compiled, a single type called TheBigClass will be created with two methods, MethodOne() and MethodTwo().
If any of the following keywords are used in describing the class, the same must apply to all partials of the same type:➤ public,➤ private,➤ protected,➤ internal,➤ abstract,➤ sealed,➤ new,➤ generic constraints
Nested partials are allowed as long as the partial keyword precedes the class keyword in the nested type.Attributes, XML comments, interfaces, generic-type parameter attributes, and members will be combined when the partial types are compiled into the type. Given these two source files ://BigClassPart1.cs
[CustomAttribute] partial class TheBigClass: TheBigBaseClass, IBigClass{public void MethodOne(){}}//BigClassPart2.cs
[AnotherAttribute]partial class TheBigClass: IOtherBigClass
{public void MethodTwo(){}}
after the compile, the equivalent source file would be:
[CustomAttribute][AnotherAttribute]
partial class TheBigClass: TheBigBaseClass, IBigClass, IOtherBigClass
{public void MethodOne(){}
public void MethodTwo(){}}
Дата добавления: 2015-09-18 | Просмотры: 525 | Нарушение авторских прав
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
|