C#2.0 -- Partial Types

19.1 Partial types

While it is good programming practice to maintain all source code for a type in a single file, sometimes a type becomes large enough that this is an impractical constraint. Furth ermore, programmers often use source code generators to produce the initial structure of an application, and then modify the resulting code. Unfortunately, when source code is emitted again sometime in the future, existing modifications are overwritten.

Partial types allow classes, structs, and interfaces to be broken into multiple pieces stored in different source files for easier development and maintenance. Additionally, partial types allow separation of machine-generated and user-written parts of types so that it is easier to augment code generated by a tool.

A new type modifier, partial, is used when defining a type in multiple parts. The following is an example of a partial class that is implemented in two parts. The two parts may be in different source files, for example because the first part is machine generated by a database mapping tool and the second part is manually authored:

public partial class Customer
{
private int id;
private string name;
private string address;
private List<Order> orders;

public Customer() {
     ...
}
}

public partial class Customer
{
public void SubmitOrder(Order order) {
     orders.Add(order);
}

public bool HasOutstandingOrders() {
     return orders.Count > 0;
}
}

When the two parts above are compiled together, the resulting code is the same as if the class had been written as a single unit:

public class Customer
{
private int id;
private string name;
private string address;
private List<Order> orders;

public Customer() {
     ...
}

public void SubmitOrder(Order order) {
     orders.Add(order);
}

public bool HasOutstandingOrders() {
     return orders.Count > 0;
}
}

All parts of a partial type must be compiled together such that the parts can be merged at compile-time. Partial types specifically do not allow already compiled types to be extended.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值