C# 标准事件模式示例

 1 using System;
 2 
 3 namespace ConsoleApp3_Test
 4 {
 5 
 6     internal class Aa
 7     {
 8 
 9         static void Main(string[] args)
10         {
11             Stock stock = new Stock("THPW"); 
12             stock.Price = 27.10M;
13 
14             //Register with the PriceChanged event
15             stock.PriceChanged += stock_PriceChanged;
16             stock.Price = 31.59M;
17         }
18 
19         static void stock_PriceChanged(object sender, PriceChangedEventArgs e)
20         {
21             Console.WriteLine($"LastPrice:{e.LastPrice}\t\tNewPrice:{e.NewPrice}");
22 
23             if (e.LastPrice != 0 && (e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
24                 Console.WriteLine("Alert, 10% stock price increase!");
25 
26             Console.WriteLine();
27         }
28     }
29 
30     public class PriceChangedEventArgs : EventArgs
31     {
32         public readonly decimal LastPrice;
33         public readonly decimal NewPrice;
34 
35         public PriceChangedEventArgs(decimal lastPrice, decimal newPrice)
36         {
37             LastPrice = lastPrice;
38             NewPrice = newPrice;
39         }
40     }
41 
42     public class Stock
43     {
44         string symbol;
45         decimal price;
46         public Stock(string symbol) { this.symbol = symbol; }
47 
48         public event EventHandler<PriceChangedEventArgs> PriceChanged;
49 
50         protected virtual void OnPriceChanged(PriceChangedEventArgs e)
51         {
52             PriceChanged?.Invoke(this, e);
53         }
54 
55         public decimal Price
56         {
57             get { return price; }
58             set
59             {
60                 if (price == value) return;
61                 decimal oldPrice = price;
62                 price = value;
63                 OnPriceChanged(new PriceChangedEventArgs(oldPrice, price));
64             }
65         }
66     }
67 }

 

posted @ 2024-09-13 11:03  竹楼风雨声  阅读(1)  评论(0编辑  收藏  举报