Although declaring one class per source file is the best-practice policy in the software
industry, a class declaration may grow so large that it becomes unwieldy to store it in
a single file. In that case, the class is better divided among more than one file to ease
development, testing, and maintenance. Using the prefix partial before the class name,
different parts of a class can be distributed across different files. Two key restrictions,
however, must be satisfied. First, all parts of a partial type must be compiled together in
order to be merged at compile-time and second, already compiled types are not allowed
to be extended to include other partial types. As an example, the partial class Parser is
implemented in three separate files (parts) as shown here:
ParserCompilationUnit.cs file (Part 1):
public partial class Parser {
private ILexer lexer;
private IReportable errorReporter;
private ISymbolTable symbolTable;
// ...
// Compilation Unit productions
void ParseCompilationUnit() { ... }
void ParseNamespace() { ... }
// ...
}
ParserClass.cs file (Part 2):
public partial class Parser {
// Class productions
void ParseClassDecl() { ... }
void ParseClassMemberDecl() { ... }
// ...
}
ParserExpr.cs file (Part 3):
public partial class Parser {
// Expression productions
void ParseExpr() { ... }
void ParseExprList() { ... }
// ...
}
When the preceding files are compiled together, the resulting code is the same as if the
class had been written as a single source file Parser.cs:
public class Parser {
private ILexer lexer;
private IReportable errorReporter;
private ISymbolTable symbolTable;
// ...
// Compilation Unit productions
void ParseCompilationUnit() { ... }
void ParseNamespace() { ... }
// ...
// Class productions
void ParseClassDecl() { ... }
void ParseClassMemberDecl() { ... }
// ...
// Expression productions
void ParseExpr() { ... }
void ParseExprList() { ... }
// ...
}
The notion of partial classes also applies to other types, such as structures and interfaces.
No comments :
Post a Comment