{ public delegate void TestDelegate(string s); public interface ITest { // 【區(qū)別】 1. event可以用在interface中,,而plain delegate不可以(因為它是field) event TestDelegate TestE; // Passed TestDelegate TestD; // Error: Interfaces cannot contain fields } public class Parent { public event TestDelegate TestE; public TestDelegate TestD; protected void RaiseTestE(string s) { TestE(s); // The event 'EventAndDelegate.Parent.TestE' can only // be used from within the type 'EventAndDelegate.Parent' } } public class Child : Parent { void ChildFunc() { // 【區(qū)別】 2. event不允許在聲明它的class之外(即使是子類)被調(diào)用(除此之外只能用于+=或-=),,而plain delegate則允許 TestD("OK"); // Passed TestE("Failure"); // Error: The event 'EventAndDelegate.Parent.TestE' can only appear on // the left hand side of += or -= (except when used from within // the type 'EventAndDelegate.Parent') // 【補充】 在子類中要觸發(fā)父類聲明的event,,通常的做法是在父類中聲明一個protected的Raisexxx方法供子類調(diào)用 RaiseTestE("OK"); // The class 'EventAndDelegate.Child' can only call the // 'EventAndDelegate.ParentRaiseTestE' method to raise the event // 'EventAndDelegate.Parent.TestE' // 【區(qū)別】 同2# object o1 = TestD.Target; object o2 = TestE.Target; // The class 'EventAndDelegate.Child' can only call the // 'EventAndDelegate.ParentRaiseTestE' method to raise the event // 'EventAndDelegate.Parent.TestE' // 【區(qū)別】 同2# TestD.DynamicInvoke("OK"); TestE.DynamicInvoke("OK"); // The class 'EventAndDelegate.Child' can only call the // 'EventAndDelegate.ParentRaiseTestE' method to raise the event // 'EventAndDelegate.Parent.TestE' } } class Other { static void Main(string[] args) { Parent p = new Parent(); p.TestD += new TestDelegate(p_Test1); // Passed p.TestE += new TestDelegate(p_Test1); // Passed // 【區(qū)別】 3. event不允許使用賦值運算符,,而plain delegate則允許,。 // 注意,,對plain delegate,,使用賦值運算符意味著進行了一次替換操作! p.TestD = new TestDelegate(p_Test2); // Passed p.TestE = new TestDelegate(p_Test2); // Error: The event 'EventAndDelegate.Parent.TestE' can only appear on // the left hand side of += or -= (except when used from within // the type 'EventAndDelegate.Parent') // 【區(qū)別】 同2# p.TestD("OK"); // Passed p.TestE("Failure"); // Error: The event 'EventAndDelegate.Parent.TestE' can only appear on // the left hand side of += or -= (except when used from within // the type 'EventAndDelegate.Parent') } static void p_Test1(string s) { Console.WriteLine("p_Test1: " + s); } static void p_Test2(string s) { Console.WriteLine("p_Test2: " + s); } } } |
|
來自: ThinkTank_引擎 > 《基礎(chǔ)》