Partial Type
ASP.NET 2.0和Avalon都使用了Partial Class. 这样用户的代码和工具生成的代码可以共同组成一个Class.对Partial Type的支持来自编译器. 4个要点如下:
- 我们把partial 叫做modifier而不是关键字.
- 同一类型在不同文件里面都需要使用partial
- 可以只在一个文件,两个文件,或者更多文件中使用partial
- Base class只需要声明一次;若多次声明必需完全一致.
例子:
Contact1.cs
using System;
namespace Realize.Net.Potential.Sample1
{
public partial class Contact
{
public Contact(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
int partial = 0;
private void PartialIsNotAKeyword()
{
partial++;
}
}
public partial class AdvancedContact: Contact
{
public AdvancedContact(string firstName, string lastName, string address) : base(firstName, lastName)
{
this.address = address;
}
}
}
Contact2.cs
using System;
namespace Realize.Net.Potential.Sample1
{
public partial class Contact
{
string firstName;
string lastName;
}
}
Contact3.cs
using System;
namespace Realize.Net.Potential.Sample1
{
public partial class Contact
{
public virtual string Name
{
get { return firstName + " " + lastName; }
}
}
public partial class AdvancedContact
{
string address;
public override string Name
{
get
{
return base.Name + " at " + address;
}
}
}
}
MainFun.cs
using System;
namespace Realize.Net.Potential.Sample1
{
public class MainFunc
{
[STAThread]
static int
{
Contact contact = new Contact("Zhanbo", "Sun");
Console.WriteLine(contact.Name);
AdvancedContact advContact = new AdvancedContact("Zhanbo", "Sun", "
Console.WriteLine(advContact.Name);
return 0;
}
}
}
To Compile:
csc /out:MySample1.exe /t:exe *.cs
深入了解Generics, iterators, anonymous methods, and partial classes的最佳读本就是更新的C#2.0Specification.