您的位置:首页 > 编程语言 > C#

C#事件——对委托的封装

2017-03-13 09:17 435 查看
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# 语言机制内部是有这个对委托的封装过程的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 事件 委托