事件event用于不同模块之间的通讯,本实例中,定义2个class,一个PublisherClass类申明了2个事件,2个方法,调用方法将会触发事件,通过股票代码code或者板块block查询股票信息。另一个SubscriberClass类,定义了一个List<Stock>成员用来保存股票Stock对象,2个方法注册给PublisherClass类对象的事件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventDemo
{
class Program
{
static void Main(string[] args)
{
List<Stock> stocks = new List<Stock>()
{
new Stock("002211", "长城科技", 11.1, "消费电子"),
new Stock("300121", "桔子电子", 22.2, "消费电子"),
new Stock("600006", "远东能源", 33.3, "能源板块"),
new Stock("600101", "望城食品", 44.4, "食品板块")
};
// 实例化2个对象
PublisherClass publisher = new PublisherClass();
SubscriberClass subscriber = new SubscriberClass(stocks);
// 事件注册
// 整个流程来看,要使用事件需申明委托、申明事件、注册事件、触发事件4个步骤
publisher.GetInfoFromCodeEvent += subscriber.ReplyToInputCode;
publisher.GetInfoFromBlockEvent += subscriber.ReplyToInputBlock;
// 触发事件,输入代码查询股票信息
publisher.GetInfoFromCode("300121");
// 触发事件,输入板块查询股票信息
publisher.GetInfoFromBlock("消费电子");
Console.ReadLine();
}
}
// 委托申明
public delegate void GetInfoFromCodeEventHandler(string code);
public delegate void GetInfoFromBlockEventHandler(string block);
// 事件发布者
public class PublisherClass
{
// 事件申明,事件类型是委托类型
public event GetInfoFromCodeEventHandler GetInfoFromCodeEvent;
public event GetInfoFromBlockEventHandler GetInfoFromBlockEvent;
public void GetInfoFromCode(string code)
{
GetInfoFromCodeEvent?.Invoke(code);
}
public void Ge