标准事件:指的是System命名空间下的EventHandler委托类型。
public delegate void EventHandler(object sender,EventArgs e);
特点:EventHandler委托的返回值是void。
第一个参数用来保存触发事件的对象引用。Object类型可以匹配任何类型的对象。 第二个参数用来保存状态信息,指明什么类型适用于当前事件。EventArgs类本身不能传递任何数据,它用于不需要传递数据的事件处理程序。
不传递数据的EventHandler实例
订阅者:
internal class Consumer
{
public string name;
public Consumer(string name)
{
this.name = name;
}
//public void GetNewTeaInfo(string teaName, float teaPrice)
//{
// Console.WriteLine("{0}订阅者收到新茶消息,品种:{1},价格:{2}",name,teaName,teaPrice);
//}
public void GetNewTeaInfo(object sender, EventArgs eventArgs)
{
Console.WriteLine("{0}订阅者收到新茶消息", this.name);
}
}
发布者:
internal class TeaShop
{
private string teaShopName;
public TeaShop(string teaName)
{
this.teaShopName = teaName;
}
public event EventHandler NewTeaEvent;
public void NewTeaCome(string teaName, float teaPrice)
{
Console.WriteLine("{0}:好消息,新茶上市!品种:{1},价格:{2}", teaShopName,teaName,teaPrice);
if(NewTeaEvent != null)
{
NewTeaEvent(this,EventArgs.Empty);
}
}
}
主程序:
internal class Program
{
static void Main(string[] args)
{
TeaEvent();
Console.ReadLine();
}
static void TeaEvent()
{
TeaShop teaShop = new TeaShop("东城茶叶");
Consumer consumer = new Consumer("聂宝根");
teaShop.NewTeaEvent += consumer.GetNewTeaInfo;
teaShop.NewTeaCome("龙井",100);
}
}
传递数据的EventHandler实例
如果需要在触发事件时传递数据,必须声明一个派生自EventArgs的类。在这个派生类中使用合适的字段保存需要传递的数据。
public delegate void EventHandler<TEventArgs>(object sender,TEventArgs e);
尽管EventArgs类并不传递数据,但它是EventHandler委托模式的重要部分。不管参数使用的实际类型是什么,object类和EventArgs类总是基类。这样EventHandler就能提供一个对所有事件和事件处理程序都通用的签名,只允许两个参数,而不是各自有不同的签名。
订阅者
internal class Consumer
{
public string name;
public Consumer(string name)
{
this.name = name;
}
//public void GetNewTeaInfo(string teaName, float teaPrice)
//{
// Console.WriteLine("{0}订阅者收到新茶消息,品种:{1},价格:{2}",name,teaName,teaPrice);
//}
public void GetNewTeaInfo(object sender, TeaEventArgs eventArgs)
{
Console.WriteLine("{0}订阅者收到新茶消息,品种:{1},价格:{2}", this.name,eventArgs.teaName,eventArgs.teaPrice);
}
}
发布者
internal class TeaShop
{
private string teaShopName;
public TeaShop(string teaName)
{
this.teaShopName = teaName;
}
public event EventHandler<TeaEventArgs> NewTeaEvent;
public void NewTeaCome(string teaName, float teaPrice)
{
Console.WriteLine("{0}:好消息,新茶上市!品种:{1},价格:{2}", teaShopName,teaName,teaPrice);
if(NewTeaEvent != null)
{
//创建
TeaEventArgs eventArgs = new TeaEventArgs(teaName, teaPrice);
NewTeaEvent(this, eventArgs);
}
}
}
主程序
internal class Program
{
static void Main(string[] args)
{
TeaEvent();
Console.ReadLine();
}
static void TeaEvent()
{
TeaShop teaShop = new TeaShop("东城茶叶");
Consumer consumer = new Consumer("聂宝根");
teaShop.NewTeaEvent += consumer.GetNewTeaInfo;
teaShop.NewTeaCome("龙井",100);
}
}
TeaEventArgs
internal class TeaEventArgs:EventArgs
{
//字段,
public string teaName;
public float teaPrice;
public TeaEventArgs(string teaName, float teaPrice)
{
this.teaName = teaName;
this.teaPrice = teaPrice;
}
}