请参考这个地址,本人写的下面参考不大,当时看的B站视频,截图只是方便我自己回忆,请看如下地址
委托和事件这篇文章写的挺好,跟着写一遍就可以懂。





针对于Broadcaster类型里面的代码,PriceChanged就相当于是委托。







例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 事件event
{
public delegate void PriceChangedHandler(decimal oldPrice,decimal newPrice);
//用来传递消息
public class PriceChangedEbentArgs : EventArgs
{
public readonly decimal LastPrice;
public readonly decimal NewPrice;
public PriceChangedEbentArgs(decimal lastPrice, decimal newPrice)
{
LastPrice = lastPrice;
NewPrice = newPrice;
}
}
public class Stock
{
string symbol;
decimal price;
public Stock(string symbol)
{
this.symbol = symbol;
}
public event EventHandler<PriceChangedEbentArgs> PriceChanged;
protected virtual void OnPriceChanged(PriceChangedEbentArgs e)
{
PriceChanged?.Invoke(this,e);
}
public decimal Price
{
get { return price; }
set
{
if (price == value) return;
decimal oldPric = price;
price = value;
OnPriceChanged(new PriceChangedEbentArgs(oldPric,price));
}
}
}
class Program
{
public event PriceChangedHandler PriceChanged;
static void Main(string[] args)
{
Stock stock = new Stock("MSFT");
stock.Price = 120;
stock.PriceChanged += stock_PriceChanged;
stock.Price = 135;
Console.ReadKey();
}
static void stock_PriceChanged(object sendr,PriceChangedEbentArgs e)
{
if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M) {
Console.WriteLine("Alert,10% stock price increase!");
}
}
}
}






本文通过一个股票价格变动的例子介绍了C#中的委托和事件的使用方式。定义了一个PriceChangedHandler委托,并创建了PriceChanged事件,当股票价格发生变化时触发此事件,通过事件处理器实现价格变动超过10%时的报警功能。
2118

被折叠的 条评论
为什么被折叠?



