C#中,正如属性是对成员变量的封装,事件是对委托的封装。
完整的事件流程:
class Program
{
static void Main(string[] args)
{
EventSender sender = new EventSender();
EventRevicer revicer = new EventRevicer();
sender.myEvent += revicer.Action;
//invoke the event
sender.Active(new MyEventArgs("C# Event"));
}
}
class MyEventArgs:EventArgs
{
public MyEventArgs(string name)
{
this.name = name;
}
public string name { get; set; }
}
delegate void MyEventHandler(EventSender sender,MyEventArgs e);
class EventSender
{
private MyEventHandler myEventHandler;
public event MyEventHandler myEvent
{
add
{
myEventHandler += value;
}
remove
{
myEventHandler -= value;
}
}
public void Active(MyEventArgs e)
{
Console.WriteLine("I send the notification");
myEventHandler.Invoke(this, e);
}
}
class EventRevicer
{
internal void Action(EventSender sender, MyEventArgs e)
{
Console.WriteLine("I get the notification!");
}
}
简写的事件流程:
class Program
{
static void Main(string[] args)
{
EventSender sender = new EventSender();
EventRevicer revicer = new EventRevicer();
sender.myEvent += revicer.Action;
//invoke the event
sender.Active(new MyEventArgs("C# Event"));
}
}
class MyEventArgs : EventArgs
{
public MyEventArgs(string name)
{
this.name = name;
}
public string name { get; set; }
}
class EventSender
{
public event EventHandler myEvent;//the event
public void Active(MyEventArgs e)
{
Console.WriteLine("I send the notification");
myEvent.Invoke(this, e);
}
}
class EventRevicer
{
internal void Action(object sender, EventArgs e)
{
//Type convert
MyEventArgs args = e as MyEventArgs;
Console.WriteLine("I get the notification! args:{0}",args.name);
}
}
注:我们平时经常用的简写流程中省略了事件封装的过程,但实际上C# 语言机制内部是有这个对委托的封装过程的。