这篇文章主要介绍了C# 标准事件流的实例代码,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
服装价格变动,触发淘宝发布活动和消费者购买衣服事件流
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# 标准事件流的资料请关注得得之家其它相关文章!
织梦狗教程
本文标题为:C# 标准事件流实例代码


基础教程推荐
猜你喜欢
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- 实例详解C#实现http不同方法的请求 2022-12-26
- Unity shader实现高斯模糊效果 2023-01-16
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#中的Linq to JSON操作详解 2023-06-08
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C# 解析XML和反序列化的示例 2023-04-14