熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

NET委托:一個關於C#的睡前故事[2]

2013-11-13 12:15:52  來源: .NET編程 
    於是彼得意識到接口雖然在很多情況都很有用但是當用作事件時粒度不夠好他希望能夠僅在別人想要時才通知他們於是他決定把接口的方法分離為單獨的委托每個委托都像一個小的接口方法

delegate void WorkStarted();
delegate void WorkProgressing();
delegate int WorkCompleted();

class Worker {
 public void DoWork() {
  ConsoleWriteLine(工作: 工作開始);
  if( started != null ) started();

  ConsoleWriteLine(工作: 工作進行中);
  if( progressing != null ) progressing();

  ConsoleWriteLine(工作: 工作完成);
  if( completed != null ) {
   int grade = completed();
   ConsoleWriteLine(工人的工作得分= + grade);
  }
 }
 public WorkStarted started;
 public WorkProgressing progressing;
 public WorkCompleted completed;
}

class Boss {
 public int WorkCompleted() {
  ConsoleWriteLine(Better);
  return ; /* 總分為 */
 }
}

class Universe {
 static void Main() {
  Worker peter = new Worker();
  Boss boss = new Boss();
  petercompleted = new WorkCompleted(bossWorkCompleted);
  peterDoWork();

  ConsoleWriteLine(Main: 工人工作完成);
  ConsoleReadLine();
 }
}

 

 靜態監聽者

  這樣彼得不會再拿他老板不想要的事件來煩他老板了但是他還沒有把宇宙放到他的監聽者列表中因為宇宙是個包涵一切的實體看來不適合使用實例方法的委托(想像一下實例化一個宇宙要花費多少資源…於是彼得就需要能夠對靜態委托進行掛鉤委托對這一點支持得很好

class Universe {
 static void WorkerStartedWork() {
  ConsoleWriteLine(Universe notices worker starting work);
 }

 static int WorkerCompletedWork() {
  ConsoleWriteLine(Universe pleased with workers work);
  return ;
 }

 static void Main() {
  Worker peter = new Worker();
  Boss boss = new Boss();
  petercompleted = new WorkCompleted(bossWorkCompleted);
  peterstarted = new WorkStarted(UniverseWorkerStartedWork);
  petercompleted = new WorkCompleted(UniverseWorkerCompletedWork);
  peterDoWork();

  ConsoleWriteLine(Main: 工人工作完成);
  ConsoleReadLine();
 }
}

[]  []  []  


From:http://tw.wingwit.com/Article/program/net/201311/15529.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.