publicclass Parent { publicevent TestDelegate TestE; public TestDelegate TestD;
protectedvoid RaiseTestE(string s) { TestE(s); // The event 'EventAndDelegate.Parent.TestE' can only // be used from within the type 'EventAndDelegate.Parent' } }
publicclass Child : Parent { void ChildFunc() { // 【区别】 2. event不允许在声明它的class之外(即使是子类)被调用(除此之外只能用于+=或-=),而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')
// 【补充】 在子类中要触发父类声明的event,通常的做法是在父类中声明一个protected的Raisexxx方法供子类调用 RaiseTestE("OK"); // The class 'EventAndDelegate.Child' can only call the // 'EventAndDelegate.ParentRaiseTestE' method to raise the event // 'EventAndDelegate.Parent.TestE'
// 【区别】 同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'
// 【区别】 同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 { staticvoid Main(string[] args) { Parent p =new Parent();
// 【区别】 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')
// 【区别】 同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') }