C# 标准事件流实例代码
程序员文章站
2022-07-05 12:55:46
服装价格变动,触发淘宝发布活动和消费者购买衣服事件流public class eventstandard { public class clothes { ///
服装价格变动,触发淘宝发布活动和消费者购买衣服事件流
public class eventstandard { public class clothes { /// <summary> /// 服装编码 /// </summary> public string id { get; set; } /// <summary> /// 服装名称 /// </summary> public string name { get; set; } /// <summary> /// 服装价格 /// </summary> private double _price; public double price { get { return this._price; } set { pricerisehandler?.invoke(this, new priceeventargs() { oldprice = this._price, newprice = value }); this._price = value; } } /// <summary> /// 服装价格变动事件 /// </summary> public event eventhandler pricerisehandler; } /// <summary> /// 衣服价格事件参数 一般会为特定的事件去封装个参数类型 /// </summary> public class priceeventargs : eventargs { public double oldprice { get; set; } public double newprice { get; set; } } public class taobao { /// <summary> /// 淘宝订户 /// </summary> public void publishpriceinfo(object sender, eventargs e) { clothes clothes = (clothes)sender; priceeventargs args = (priceeventargs)e; if (args.newprice < args.oldprice) console.writeline($"淘宝:发布衣服价格下降的公告,{clothes.name}服装直降{args.oldprice - args.newprice}元,限时抢购!"); else console.writeline("淘宝:价格悄悄上涨或价格未变化,啥也不做"); } } public class consumer { /// <summary> /// 消费者订户 /// </summary> public void buy(object sender, eventargs e) { clothes clothes = (clothes)sender; priceeventargs args = (priceeventargs)e; if (args.newprice < args.oldprice) console.writeline($"消费者:之前价格{args.oldprice},现在价格{args.newprice},果断买了!"); else console.writeline($"消费者:等等看,降价了再说"); } } public static void show() { clothes clothes = new clothes() { id = "12111-xk", name = "优衣库", price = 128 }; //订阅:把订户和发布者的事件关联起来 clothes.pricerisehandler += new taobao().publishpriceinfo; clothes.pricerisehandler += new consumer().buy; //价格变化,自动触发订户订阅的事件 clothes.price = 300; } }
调用:
clothes.price = 300; eventstandard.show();
clothes.price = 98; eventstandard.show();
以上就是c# 标准事件流实例代码的详细内容,更多关于c# 标准事件流的资料请关注其它相关文章!