在什么情况下此事件将为空?

In what scenario will this event be null?

我正在使用 MVP 模式构建应用程序。为了让演示者发生事情,我在视图中创建事件,演示者将监视它们。 ReSharper 向我发出有关可能的 null 引用异常的警告,并且我看到了在触发事件之前检查 null 的教程。事件究竟以何种方式可以为空?下面是我的代码示例:

public partial class PrinterSelectView : Form, IPrinterSelectView
{
    public PrinterSelectView()
    {
        InitializeComponent();
    }

    public event Action Canceled;
    public event Action Saved;

    private void btnCancelClick(object sender, EventArgs e)
    {
        if(Canceled != null)
        {
            Canceled();
        }
    }

}

如果没有代码注册该事件(调用 Canceled += <some code>),则该事件将为空。检查确保在触发事件之前有任何注册的侦听器。

默认情况下它们始终为空。该对象的调用者可以稍后订阅事件,例如:

var view = new PrinterSelectView();
view.Canceled += OnCanceled; // now it's not null

但之前,或者如果调用者从未订阅您的事件将为空。

防止此类警告的一种通用方法是始终自己为其分配一个空委托,例如:

public partial class PrinterSelectView : Form, IPrinterSelectView
{
    public event Action Canceled = () => { }; // will never be null now
    public event Action Saved = () => { };
    // ...
}

这只是为两个事件分配了一个空的 lambda 表达式,这让您可以假设事件永远不会为空。