1.委派的實現(xiàn)過程。 首先來看一下委派,委派其實就是方法的傳遞,并不定義方法的實現(xiàn)。事件其實就是標準化了的委派,為了事件處理過程特制的、稍微專業(yè)化一點的組播委派(多點委派)。下面舉一個例子,我覺得把委派的例子和事件的例子比較,會比較容易理解。 using System; class Class1 { delegate int MathOp(int i1,int i2); static void Main(string[] args) { MathOp op1=new MathOp(Add); MathOp op2=new MathOp(Multiply); Console.WriteLine(op1(100,200)); Console.WriteLine(op2(100,200)); Console.ReadLine(); } public static int Add(int i1,int i2) { return i1+i2; } public static int Multiply(int i1,int i2) { return i1*i2; } } 首先代碼定義了一個委托MathOp,其簽名匹配與兩個函數(shù)Add()和Multiply()的簽名(也就是其帶的參數(shù)類型數(shù)量相同): delegate int MathOp(int i1,int i2); Main()中代碼首先使用新的委托類型聲明一個變量,并且初始化委托變量.注意,聲明時的參數(shù)只要使用委托傳遞的函數(shù)的函數(shù)名,而不加括號: MathOp op1=new MathOp(Add); (或為MathOp op1=new MathOp(Multiply);) 委托傳遞的函數(shù)的函數(shù)體: public static int Add(int i1,int i2) { return i1+i2; } public static int Multiply(int i1,int i2) { return i1*i2; } 然后把委托變量看作是一個函數(shù)名,將參數(shù)傳遞給函數(shù)。 Console.WriteLine(op1(100,200)); Console.WriteLine(op2(100,200)); 2.事件的實現(xiàn)過程 using System; class Class1 { static void Main(string[] args) { Student s1=new Student(); Student s2=new Student(); s1.RegisterOK +=new Student.DelegateRegisterOkEvent(Student_RegisterOK); s2.RegisterOK +=new Student.DelegateRegisterOkEvent(Student_RegisterOK); s1.Register(); s2.Register(); Console.ReadLine(); } static void Student_RegisterOK() { Console.WriteLine("Hello"); } } class Student { public delegate void DelegateRegisterOkEvent(); public event DelegateRegisterOkEvent RegisterOK; public string Name; public void Register() { Console.WriteLine("Register Method"); RegisterOK(); } } 在Student類中,先聲明了委托DelegateRegisterOkEvent(),然后使用event和要使用的委托類型(前面定義的DelegateRegisterOkEvent委托類型)聲明事件RegisterOK(可以看作是委托的一個實例。): public delegate void DelegateRegisterOkEvent(); public event DelegateRegisterOkEvent RegisterOK; 然后在Main()函數(shù)中,實例化Student類,然后s1.RegisterOK事件委托給了Student_RegisterOK 方法。通過“+=”(加等于)操作符非常容易地為.Net對象中的一個事件添加一個甚至多個響應方法;還可以通過非常簡單的“-=”(減等于)操作符取消這些響應方法。 然后,當調(diào)用s1.Register()時,事件s1.RegisterOK發(fā)生。
|