EventArgs可以为null吗?

时间:2016-06-30 12:09:14

标签: c# .net events

我的一些代码和代码分析中有protected override void OnFormClosing(FormClosingEventArgs e)给出CA1062,因为我不检查e是否为空。

惯例是EventArgs永远不应该为空;这就是我们EventArgs.Empty的原因。当然,我可能是愚蠢的,并在提出一些事件时传递null而不是EventArgs.Empty,但是这里会有一些自动生成的代码,它会引发FormClosing事件,所以我只是压制了警告。 / p>

是否存在一些可能导致EventArgs被框架置空而不是由程序员引起的极端情况?

1 个答案:

答案 0 :(得分:5)

简短回答:是的,你可以这样做:

public void DoSomething()
{
    OnFormClosing(null);
}

但除非你真的这样做,否则你可以忽略警告。

查看类Form的源代码,我们可以找到this method,其中包含以下内容:

    /// <devdoc>
    ///    <para>Raises the FormClosing event for this form when Application.Exit is called.
    ///          Returns e.Cancel returned by the event handler.</para>
    /// </devdoc>
    internal bool RaiseFormClosingOnAppExit() {
        FormClosingEventArgs e = new FormClosingEventArgs(CloseReason.ApplicationExitCall, false);
        OnFormClosing(e);
        return e.Cancel;
    }

所以不,当WinForms引发事件时,e无法为null。