考虑以下示例。
每次股票价格发生变化时,该类都会Stock
触发其事件:PriceChanged
public delegate void PriceChangedHandler (decimal oldPrice,decimal newPrice);
public class Stock
{
string symbol;
decimal price;
public Stock (string symbol) { this.symbol = symbol; }
public event PriceChangedHandler PriceChanged;
public decimal Price
{
get { return price; }
set
{
if (price == value) return; // Exit if nothing has changed
if (PriceChanged != null) // If invocation list not empty,
PriceChanged (price, value); // fire event.
price = value;
}
}
}
如果我们从示例中删除 event 关键字,使其PriceChanged
成为普通的委托字段,我们的示例将给出相同的结果。但是,Stock
会不太健壮,
我的问题是 event 关键字以何种方式使股票更加稳健?