创建包含其他数据的自定义 EventArgs
自定义事件通常需要包含有关事件信息的自定义事件参数。例如 MouseEventArgs 其用于通过像 MouseDown 或 MouseUp 事件鼠标事件,包含关于用于生成事件 Location 或 Buttons 信息。
创建新事件时,要创建自定义事件 arg:
- 创建一个派生自
EventArgs的类,并定义必要数据的属性。 - 作为惯例,类的名称应以
EventArgs结尾。
例
在下面的示例中,我们为类的 Price 属性创建了 PriceChangingEventArgs 事件。事件数据类包含 CurrentPrice 和 NewPrice。当你为 Price 属性分配新值并让消费者知道价值正在变化并让他们知道当前价格和新价格时,该事件会引发:
PriceChangingEventArgs
public class PriceChangingEventArgs : EventArgs
{
public PriceChangingEventArgs(int currentPrice, int newPrice)
{
this.CurrentPrice = currentPrice;
this.NewPrice = newPrice;
}
public int CurrentPrice { get; private set; }
public int NewPrice { get; private set; }
}
产品
public class Product
{
public event EventHandler<PriceChangingEventArgs> PriceChanging;
int price;
public int Price
{
get { return price; }
set
{
var e = new PriceChangingEventArgs(price, value);
OnPriceChanging(e);
price = value;
}
}
protected void OnPriceChanging(PriceChangingEventArgs e)
{
var handler = PriceChanging;
if (handler != null)
handler(this, e);
}
}
你可以通过允许使用者更改新值来增强该示例,然后将该值用于属性。为此,只需在类中应用这些更改即可。
将 NewPrice 的定义更改为可设置:
public int NewPrice { get; set; }
在调用 OnPriceChanging 之后,将 Price 的定义更改为使用 e.NewPrice 作为属性值:
int price;
public int Price
{
get { return price; }
set
{
var e = new PriceChangingEventArgs(price, value);
OnPriceChanging(e);
price = e.NewPrice;
}
}