C# 标准事件(Event)实现
一、委托(gelegate)与事件的关系(Event)
1、委托是一种类型,事件是委托的实例 (有限制的实例)。
2、事件不能=方法,也不能=null
3、事件,在类的内部根据条件判断执行,事件是一个开放的接口,订阅方可以添加个订户。
二、代码实现
1、事件的发布者,发布事件并且在满足条件上的时候,触发事件
public class iPhonex { public int Id { get; set; } public string Name { get; set; } /// <summary> /// 价格发生变打折后触发事件 /// </summary> private int _price; public int Price { get { return this._price; } set { if (value < this._price) { this.MyEventHandler?.Invoke(this, new xEventArgs() { OldPrice = this.Price,NewPrice=value }); } this._price = value; } } /// <summary> /// 打折事件 事件发布 /// </summary> public event EventHandler MyEventHandler; //定义标准版 }
*****事件参数 一般会为特定的事件去封装个参数类型
public class xEventArgs : EventArgs { public int OldPrice { get; set; } public int NewPrice { get; set; } }
2、订户
public class iphoneWholesaler { public void Buy(object obj, EventArgs e) { iPhonex iPhonex = (iPhonex)obj; Console.WriteLine($"this is { iPhonex.Name}"); xEventArgs args = (xEventArgs)e; Console.WriteLine($"iphone 之前的价格 { args.OldPrice}"); Console.WriteLine($"iphone 之后的价格 { args.NewPrice}"); Console.WriteLine($"iphone 大降价,要囤货了"); } }
public class Student { public void Buy(object obj, EventArgs e) { iPhonex iPhonex = (iPhonex)obj; Console.WriteLine($"this is { iPhonex.Name}"); xEventArgs args = (xEventArgs)e; Console.WriteLine($"iphone 之前的价格 { args.OldPrice}"); Console.WriteLine($"iphone 之后的价格 { args.NewPrice}"); Console.WriteLine($"iphone 买了"); } }
3、订阅事件
public static void Show() { iPhonex iPhonex = new iPhonex { Id=1,Name="苹果手机", Price=2000 }; //订阅事件 iPhonex.MyEventHandler += new Student().Buy; iPhonex.MyEventHandler += new iphoneWholesaler().Buy; iPhonex.Price = 2100; iPhonex.Price = 1888; }
观察者模式的实现
浙公网安备 33010602011771号