东哥技术专栏 - Coldwine's Blog

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::


Partial Type

ASP.NET 2.0和Avalon都使用了Partial Class. 这样用户的代码和工具生成的代码可以共同组成一个Class.对Partial Type的支持来自编译器. 4个要点如下:

  1. 我们把partial 叫做modifier而不是关键字.
  2. 同一类型在不同文件里面都需要使用partial
  3. 可以只在一个文件,两个文件,或者更多文件中使用partial
  4. 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 Main (string[] args)

    {

      Contact contact = new Contact("Zhanbo", "Sun");

      Console.WriteLine(contact.Name);

      AdvancedContact advContact = new AdvancedContact("Zhanbo", "Sun", " 1 Microsoft Way ");

      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.

posted on 2005-08-12 10:13  东哥技术专栏 - Coldwine's Blog  阅读(3999)  评论(0编辑  收藏  举报