栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C# 标准事件流实例代码

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C# 标准事件流实例代码

服装价格变动,触发淘宝发布活动和消费者购买衣服事件流

public class EventStandard
  {
    public class Clothes {

      /// 
      /// 服装编码
      /// 
      public string Id { get; set; }

      /// 
      /// 服装名称
      /// 
      public string Name { get; set; }

      /// 
      /// 服装价格
      /// 
      private double _price;

      public double Price {
 get { return this._price; }
 set {
     PriceRiseHandler?.Invoke(this, new PriceEventArgs()
     {
OldPrice = this._price,
NewPrice = value
     });
   this._price = value;
 }
      }

      /// 
      /// 服装价格变动事件
      /// 
      public event EventHandler PriceRiseHandler;

    }

    /// 
    /// 衣服价格事件参数 一般会为特定的事件去封装个参数类型
    /// 
    public class PriceEventArgs : EventArgs
    {
      public double OldPrice { get; set; }
      public double NewPrice { get; set; }
    }

    public class TaoBao {
      /// 
      /// 淘宝订户
      /// 
      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
    {
      /// 
      /// 消费者订户
      /// 
      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# 标准事件流的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/121884.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号