C# 標準事件流實例代碼
更新時間:2020年07月23日 08:32:37 作者:滑豬小板
這篇文章主要介紹了C# 標準事件流的實例代碼,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
服裝價格變動,觸發(fā)淘寶發(fā)布活動和消費者購買衣服事件流
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>
/// 衣服價格事件參數(shù) 一般會為特定的事件去封裝個參數(shù)類型
/// </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($"淘寶:發(fā)布衣服價格下降的公告,{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},現(xiàn)在價格{args.NewPrice},果斷買了!");
else
Console.WriteLine($"消費者:等等看,降價了再說");
}
}
public static void Show()
{
Clothes clothes = new Clothes()
{
Id = "12111-XK",
Name = "優(yōu)衣庫",
Price = 128
};
//訂閱:把訂戶和發(fā)布者的事件關聯(lián)起來
clothes.PriceRiseHandler += new TaoBao().PublishPriceInfo;
clothes.PriceRiseHandler += new Consumer().Buy;
//價格變化,自動觸發(fā)訂戶訂閱的事件
clothes.Price = 300;
}
}
調(diào)用:
clothes.Price = 300; EventStandard.Show();

clothes.Price = 98; EventStandard.Show();

以上就是C# 標準事件流實例代碼的詳細內(nèi)容,更多關于C# 標準事件流的資料請關注腳本之家其它相關文章!
相關文章
C#實現(xiàn)圖表中鼠標移動并顯示數(shù)據(jù)
這篇文章主要為大家詳細介紹了C#實現(xiàn)圖表中鼠標移動并顯示數(shù)據(jù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
C#使用IronPython庫調(diào)用Python腳本
這篇文章介紹了C#使用IronPython庫調(diào)用Python腳本的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
C#基于TCP協(xié)議的服務器端和客戶端通信編程的基礎教程
這篇文章主要介紹了C#基于TCP協(xié)議的服務器端和客戶端通信編程的基礎教程,文中講解了C#中TCP編程主要相關的TcpListener類與TcpClient類用法,需要的朋友可以參考下2016-04-04
深入分析C#中WinForm控件之Dock順序調(diào)整的詳解
本篇文章是對C#中WinForm控件之Dock順序調(diào)整進行了詳細的分析介紹,需要的朋友參考下2013-05-05
DevExpress之ChartControl實現(xiàn)餅狀圖百分比演示實例
這篇文章主要介紹了DevExpress之ChartControl實現(xiàn)餅狀圖百分比演示的方法,實例講述了窗體與圖形繪制函數(shù)的用法,需要的朋友可以參考下2014-10-10

