public class CarDealer { public Action<string> NewCarInfo; //使用系统定义的泛型委托 public void NewCarComing(string car) { Console.WriteLine("CarDealer, new car {0} has come.", car); if (NewCarInfo != null) NewCarInfo(car); } }
先插入一段代码,这个例子的 Action<string> 表示只有一个 string 参数,如果有一组的参数的话,代码写起来会比较难看。
.Net 给我们提供了基于 EventArgs 来进行传参 的 自定义事件 EventHandler。
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
可以 EventHandler 理解为“发布者提供的订阅器”,"sender" 表示发布者,“e” 表示发布者推送给订阅者的参数信息。
而 EventArgs 则是 发布者 与 订阅者 间约定好的订阅信息。
来看完整的例子:
class Program { public class MyEventArg : EventArgs { public string name { get; set; } public MyEventArg(string carname) { name = carname; } } public class CarDealer { public event EventHandler<MyEventArg> NewCarInfo; public void NewCarComing(string carname) { Console.WriteLine("CarDealer, new car {0} has come.", carname); if (NewCarInfo != null) NewCarInfo(this, new MyEventArg(carname)); } } public class Consumer { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, MyEventArg e) { Console.WriteLine("{0}, car {1} is new", name, e.name); } } static void Main(string[] args) { var dealer = new CarDealer(); var personA = new Consumer("personA"); dealer.NewCarInfo += personA.NewCarIsHere; dealer.NewCarComing("Ferrari"); var personB = new Consumer("personB"); dealer.NewCarInfo += personB.NewCarIsHere; dealer.NewCarComing("BMW"); Console.ReadLine(); } }
个人不喜用“发布-订阅”模式来阐述,更偏向于用“通知-反馈”模式的流程 可加以总结了:
1. 定义一种事件或委托,同时约定好通知者要给反馈者的参数;
public class MyEventArg : EventArgs { public string name { get; set; } public MyEventArg(string carname) { name = carname; } } public class CarDealer { public event EventHandler<MyEventArg> NewCarInfo; public void NewCarComing(string carname) { Console.WriteLine("CarDealer, new car {0} has come.", carname); if (NewCarInfo != null) NewCarInfo(this, new MyEventArg(carname)); } }
2. 发布者提供事件通道 接受 反馈者按约定生成的反馈行为;
public class Consumer { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, MyEventArg e) { Console.WriteLine("{0}, car {1} is new", name, e.name); } }
var dealer = new CarDealer(); var personA = new Consumer("personA"); dealer.NewCarInfo += personA.NewCarIsHere; var personB = new Consumer("personB"); dealer.NewCarInfo += personB.NewCarIsHere;
3. 通知者发出通知,反馈者收到通知并做出反馈行为;
dealer.NewCarComing("Ferrari"); dealer.NewCarComing("BMW");
时间: 2024-12-08 10:03:55