日期:2008-04-21  浏览次数:20568 次

.NET Delegates: A C# Bedtime Story中文版(上篇)

作者:Chris Sells

译者:荣耀


【译注:C#进阶文章。Chris Sells是《ATL Internals》一书作者之一。译文中所有程序调试环境均为Microsoft Visual Studio.NET 7.0 Beta2和 Microsoft .NET Framework SDK Beta2。代码就是文章,请仔细阅读代码J】

类型耦合

从前,在南方的一个异国他乡,有一个叫peter的勤劳的工人。他对boss百依百顺,但他的boss却是个卑鄙无信的小人,他坚持要求peter不断汇报工作情况。由于peter不希望被boss盯着干活,于是他向boss承诺随时汇报工作进度。peter利用类型引用定期回调boss来实现这个承诺:

using System;//【译注:译者补充】

class Worker

{

     public void Advise(Boss boss)

{

_boss = boss;

}

     public void DoWork()

     {

          Console.WriteLine("Worker: work started");

          if( _boss != null ) _boss.WorkStarted();

          Console.WriteLine("Worker: work progressing");

          if( _boss != null ) _boss.WorkProgressing();

          Console.WriteLine("Worker: work completed");

          if( _boss != null )

         {

              int grade = _boss.WorkCompleted();

              Console.WriteLine("Worker grade = " + grade);

         }

     }

     private Boss _boss;

}

class Boss

{

     public void WorkStarted() { /*boss不关心. */ }

     public void WorkProgressing() { /*boss不关心. */ }

     public int WorkCompleted()

     {

          Console.WriteLine("It's about time!");

         return 2; /* out of 10 */

     }

}

class Universe

{

     static void Main()

     {

         Worker peter = new Worker();

         Boss boss = new Boss();

          peter.Advise(boss);

          peter.DoWork();

          Console.WriteLine("Main: worker completed work");

          Console.ReadLine();

     }

}

/*【译注:以下是上段程序输出结果:

Worker: work started

Worker: work progressing

Worker: work completed

It's about time!

Worker grade = 2

Main: worker completed work

】*/

接口

     现在,peter成了一个特殊人物,他不但能够忍受卑鄙的boss,和universe也建立了紧密的联系。peter感到universe对他的工作进程同样感兴趣。不幸的是,除了保证boss能够被通知外,如果不为universe添加一个特殊的通知方法和回调,peter无法向universe通知其工作进程。Peter希望能从那些通知方法的实现中分离出潜在的通知约定,为此,他决定将方法剥离到接口中:

using System; //【译注:译者补充】