using System.Collections.Generic; |
namespace Delegate_vs_Event |
public delegate string TestDelegate( string input); |
public static TestDelegate myDelegate; |
public static event TestDelegate myEvent; |
static void Main( string [] args) |
///1.在声明委托和事件的类内部,对于Delegate与Event的实例的初始化和调用操作没有任何区别; |
myDelegate = new TestDelegate(TestEvent); |
myEvent = new TestDelegate(TestEvent); |
Subject subject = new Subject(); |
Observer ob = new Observer(subject); |
static string TestEvent( string param) |
Console.WriteLine( "Hello " + param); |
public delegate void TestHandleForReg( string param); |
public event TestHandleForReg TestHandleEvent; |
public TestHandleForReg TestHandleDelegate; |
Console.WriteLine( "Call external method result:" ); |
TestHandleEvent( "Start" ); |
///2.对于Delegate与Event的实例,其订阅(Subscribe,即+=)或取消订阅(Unsubscribe,即-=)的操作没有任何区别; |
TestHandleDelegate += Method_Subject1; |
TestHandleDelegate += Method_Subject2; |
TestHandleDelegate -= Method_Subject2; |
TestHandleEvent += Method_Subject1; |
TestHandleEvent += Method_Subject2; |
TestHandleEvent -= Method_Subject2; |
Console.WriteLine( "Call internal method result by [Delegate] " ); |
TestHandleDelegate( "Delegate" ); |
Console.WriteLine( "Call internal method result by [Event] " ); |
TestHandleEvent( "Event" ); |
public void Method_Subject1( string str) |
Console.WriteLine( "Method_Subject1" ); |
public void Method_Subject2( string str) |
Console.WriteLine( "Method_Subject2" ); |
public static string Static_Method_Subject() |
return "Static_Method_Subject" ; |
public Observer(Subject subject) |
subject.TestHandleEvent += Method_Observer; |
subject.TestHandleDelegate += Method_Observer; |
///3.Delegate与Event唯一区别就在于以下2点:Event提供了更严格的封装访问控制,其目的是为了防止其他类破坏委托的多播链,故不允许在声明事件的类外初始化或调用. |
///即除了声明Event的类,其它类只能订阅(Subscribe,即+=)或取消订阅(Unsubscribe,即-=)该Event; |
///subject.TestHandleEvent = new Subject.TestHandleForReg(Method_Observer); |
/// subject.TestHandleDelegate = new Subject.TestHandleForReg(Method_Observer);///Error:The event 'Delegate_vs_Event.Subject.TestHandleEvent' can only appear on the left hand side of += or -= (except when used from within the type 'Delegate_vs_Event.Subject') |
///subject.TestHandleDelegate("test"); |
/// subject.TestHandleEvent("test");///Error:The event 'Delegate_vs_Event.Subject.TestHandleEvent' can only appear on the left hand side of += or -= (except when used from within the type 'Delegate_vs_Event.Subject') |
public void Method_Observer( string info) |
Console.WriteLine( "Observer's method [" +info+ "]" ); |
1.在声明委托和事件的类内部,对于Delegate与Event的实例的初始化和调用操作没有任何区别;
2.对于Delegate与Event的实例,其订阅(Subscribe,即+=)或取消订阅(Unsubscribe,即-=)的操作没有任何区别;
3.Delegate与Event唯一区别就在于以下2点:Event提供了更严格的封装访问控制,其目的是为了防止其他类破坏委托的多播链,故不允许在声明事件的类外初始化或调用.即除了声明Event的类,其它类只能订阅(Subscribe,即+=)或取消订阅(Unsubscribe,即-=)该Event;