たとえば、ベース イベント公開メソッドがあります。
protected virtual OnSomeEvent(EventArgs e)
{
var handler = SomeEvent;
if (handler != null)
{
handler(this, e);
// handler(this, new EventArgs());// EDIT: Yes it should be
// handler(this, e),
// ignore this one :D
}
}
OnSomeEvent
発生時に追加のイベントをオーバーライドして発生させる派生クラスの場合:
protected override OnSomeEvent(EventArgs e)
{
base.OnSomeEvent(e);
if (ExtendedEvent != null)
{
OnExtendedEvent(e);
}
}
protected void OnExtendedEvent(EventArgs e)
{
// some stuff done
// new information the ExtendedEventArgs object needs
// is not available until this point
ExtendedEvent(this, new ExtendedEventArgs(someStuff, someOtherStuff));
}
そして、派生がこのように進むと、それを必要とする派生クラスの世代ごとに新しい派生 EventArgs が作成されます。ただしEventArgs
、.NET フレームワークのさまざまな派生物は変更可能 (セッターなし) に設計されていないようです。これにより、オブジェクトが EventArgs の単一のインスタンスを保持し、それを変更することが妨げられます。
したがって、このようなイベントが発生するたびに、関連するすべてのEventArgs
オブジェクトにメモリが再割り当てされます。イベントが 1 秒間に何十回もトリガーされる可能性がある (OnPaint
コントロールのイベントなど) グラフィックが集中するアプリケーションでは、これは本当に良い方法でしょうか?
次のことが可能になるように、いくつかの変更を加えて変更可能にする必要OnExtendedEvent()
がExtendedEventArgs
ありますか?
protected ExtendedEventArgs extendedArgs = ExtendedEventArgs.Empty;
protected void OnExtendedEvent(EventArgs e)
{
// some stuff done
// new information the ExtendedEventArgs object needs
// is not available until this point
extendedArgs.someProperty1 = someStuff;
extendedArgs.someProperty2 = someOtherStuff;
ExtendedEvent(this, extendedArgs);
}
編集: サンプルコードを修正しました。より明確になるはずです。