通过代码学习C#中的事件
namespace DotNetEvents
{
using System;
using System.Collections.Generic;
//定义一个用于传递信息的类
public class CustomEventArgs : EventArgs
{
public CustomEventArgs(string s)
{
message = s;
}
private string message;
public string Message
{
get { return message; }
set { message = value; }
}
}
// 定义一个能够发布事件的类
class Publisher
{
// 通过泛型的方式定义一个事件
public event EventHandler<CustomEventArgs> RaiseCustomEvent;
public void DoSomething()
{
//激发事件
OnRaiseCustomEvent(new CustomEventArgs("Did something"));
}
//封装事件激发代码
protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
{
EventHandler<CustomEventArgs> handler = RaiseCustomEvent;
// Event will be null if there are no subscribers
if (handler != null)
{
// Format the string to send inside the CustomEventArgs parameter
e.Message += String.Format(" at {0}", DateTime.Now.ToString());
//采用()调用的方式激发事件
handler(this, e);
}
}
}
//订阅事件的类
class Subscriber
{
private string id;
public Subscriber(string ID, Publisher pub)
{
id = ID;
// Subscribe to the event using C# 2.0 syntax
pub.RaiseCustomEvent += HandleCustomEvent;
}
//响应事件函数
void HandleCustomEvent(object sender, CustomEventArgs e)
{
Console.WriteLine(id + " received this message: {0}", e.Message);
}
}
class Program
{
static void Main(string[] args)
{
Publisher pub = new Publisher();
Subscriber sub1 = new Subscriber("sub1", pub);
Subscriber sub2 = new Subscriber("sub2", pub);
// Call the method that raises the event.
pub.DoSomething();
// Keep the console window open
Console.WriteLine("Press Enter to close this window.");
Console.ReadLine();
}
}
}