我已经看到了一些关于这个习语的提及(包括SO):
// Deliberately empty subscriber
public event EventHandler AskQuestion = delegate {};
Run Code Online (Sandbox Code Playgroud)
好处很明显 - 它避免了在提升事件之前检查null的必要性.
但是,我很想知道是否有任何缺点. 例如,它是否被广泛使用并且足够透明以至于不会引起维护问题?空事件用户呼叫是否有明显的性能影响?
鉴于Reactive Extensions(Rx)框架提供的可组合事件的好处,我想知道我的类是否应该停止推送.NET事件,而是暴露Rx可观察量.
例如,使用标准.NET事件获取以下类:
public class Foo
{
private int progress;
public event EventHandler ProgressChanged;
public int Progress
{
get { return this.progress; }
set
{
if (this.progress != value)
{
this.progress = value;
// Raise the event while checking for no subscribers and preventing unsubscription race condition.
var progressChanged = this.ProgressChanged;
if (progressChanged != null)
{
progressChanged(this, new EventArgs());
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
很多单调的管道.
这个类可以使用某种observable来替换这个功能:
public class Foo
{
public Foo()
{
this.Progress = some new observable; …Run Code Online (Sandbox Code Playgroud)