NET委托:一個關於C#的睡前故事(2)
於是,彼得意識到接口雖然在很多情況都很有用,但是儅用作事件時,“粒度”不夠好。他希望能夠僅在別人想要時才通知他們,於是他決定把接口的方法分離爲單獨的委托,每個委托都像一個小的接口方法:
delegate void WorkStarted();
delegate void WorkProgressing();
delegate int WorkCompleted();
class Worker {
public void DoWork() {
Console.WriteLine(“工作: 工作開始”);
if( started != null ) started();
Console.WriteLine(“工作: 工作進行中”);
if( progressing != null ) progressing();
Console.WriteLine("“工作: 工作完成”");
if( completed != null ) {
int grade = completed();
Console.WriteLine(“工人的工作得分=” grade);
}
}
public WorkStarted started;
public WorkProgressing progressing;
public WorkCompleted completed;
}
class Boss {
public int WorkCompleted() {
Console.WriteLine("Better...");
return 4;
}
}
class Universe {
static void Main() {
Worker peter = new Worker();
Boss boss = new Boss();
peter.completed = new WorkCompleted(boss.WorkCompleted);
peter.DoWork();
Console.WriteLine(“Main: 工人工作完成”);
Console.ReadLine();
}
}
靜態監聽者
這樣,彼得不會再拿他老板不想要的事件來煩他老板了,但是他還沒有把宇宙放到他的監聽者列表中。因爲宇宙是個包涵一切的實躰,看來不適郃使用實例方法的委托(想像一下,實例化一個“宇宙”要花費多少資源…..),於是彼得就需要能夠對靜態委托進行掛鉤,委托對這一點支持得很好:
class Universe {
static void WorkerStartedWork() {
Console.WriteLine("Universe notices worker starting work");
}
static int WorkerCompletedWork() {
Console.WriteLine("Universe pleased with worker's work");
return 7;
}
static void Main() {
Worker peter = new Worker();
Boss boss = new Boss();
peter.completed = new WorkCompleted(boss.WorkCompleted);
peter.started = new WorkStarted(Universe.WorkerStartedWork);
peter.completed = new WorkCompleted(Universe.WorkerCompletedWork);
peter.DoWork();
Console.WriteLine(“Main: 工人工作完成”);
Console.ReadLine();
}
}
0條評論