.NET事件机制
1,声明事件 2,声明事件触发后所执行的代理 3,声明触发事件方法 4,订阅事件 实例:制造者与购买者
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EventDemo.NewFolder { public class CarMakerEventArgs : EventArgs { private readonly string carNumber; private readonly string carBrand; private readonly string productDate; public string CarNumber { get { return this.carNumber; } } public string CarBrand { get { return this.carBrand;} } public string ProductDate { get { return this.productDate; } } public CarMakerEventArgs(string carNumber, string carBrand, string productDate) { this.carNumber = carNumber; this.carBrand = carBrand; this.productDate = productDate; } } public class CarMaker { public delegate void CarMakerEventHandler(object sender,CarMakerEventArgs e);//声明委托代理 public event CarMakerEventHandler CarMake;//声明事件 protected virtual void OnCarMaker(CarMakerEventArgs e)//声明触发事件方法 { CarMakerEventHandler handler = CarMake; if (handler!=null) { handler(this, e); } } public void IsSureMake(string carNumber, string carBrand, string productDate) { Console.WriteLine(productDate+"量产"+carBrand+carNumber+"汽车"); OnCarMaker(new CarMakerEventArgs(productDate, carBrand, carNumber)); } } public class CarBuyer { private string buyerName; public CarBuyer(string buyerName) { this.buyerName = buyerName; } public void Buy(object sender,CarMakerEventArgs e) { Console.WriteLine(this.buyerName+"于"+"2012-12-12购买了于"+e.ProductDate+"生产的"+e.CarBrand+e.CarNumber+"汽车!"); } } }
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EventDemo.NewFolder; namespace EventDemo { class Program { static void Main(string[] args) { Demo005(); } static void Demo005() { CarMaker cm = new CarMaker(); CarBuyer cb1 = new CarBuyer("B1"); CarBuyer cb2 = new CarBuyer("B2"); cm.CarMake += new CarMaker.CarMakerEventHandler(cb1.Buy); cm.CarMake += new CarMaker.CarMakerEventHandler(cb2.Buy); cm.IsSureMake("Z4","宝马",DateTime.Now.ToString("yyyy-MM-dd")); Console.WriteLine("---------------------"); cm.CarMake -= new CarMaker.CarMakerEventHandler(cb2.Buy); cm.IsSureMake("S320", "宝马", DateTime.Now.ToString("yyyy-MM-dd")); Console.ReadKey(); } } }

浙公网安备 33010602011771号