我在书中简而言之 (http://www.albahari.com/nutshell/ch04.aspx)委托,事件惯例,我不明白
using System;
public class PriceChangedEventArgs : EventArgs
{
public readonly decimal LastPrice;
public readonly decimal NewPrice;
public PriceChangedEventArgs (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<PriceChangedEventArgs> PriceChanged;
****protected virtual void OnPriceChanged (PriceChangedEventArgs e)
{
if (PriceChanged != null) PriceChanged (this, e);
}****
public decimal Price
{
get { return price; }
set
{
if (price == value) return;
OnPriceChanged (new PriceChangedEventArgs (price, value));
price = value;
}
}
}
class Test
{
static void Main()
{
Stock stock = new Stock ("THPW");
stock.Price = 27.10M;
// register with the PriceChanged event
stock.PriceChanged += stock_PriceChanged;
stock.Price = 31.59M;
}
static void stock_PriceChanged (object sender, PriceChangedEventArgs e)
{
if ((e.NewPrice - e.LastPrice)/e.LastPrice > 0.1M)
Console.WriteLine ("Alert, 10% stock price increase!");
}
}
我不明白,这就是为什么使用这个惯例看这个例子从C#
..
****protected virtual void OnPriceChanged (PriceChangedEventArgs e)
{
if (PriceChanged != null) PriceChanged (this, e);
}****
为什么我需要这种方法,为什么我会关心给它“this”参数?!?不能,我只是将该类中的事件与测试类中的方法PriceChanged直接相连并跳过该方法?!?
你怎么会重视吗?该方法正在附加。您不必使用该方法,只需使用其中的代码,即可代替所需的位置。 – 2011-12-29 19:34:17