我在書中簡而言之 (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