我protected override void OnFormClosing(FormClosingEventArgs e)在我的一些代码和代码分析中给出了一个CA1062,因为我不检查是否e为null.
公约EventArgs永远不应该是空的; 这就是为什么我们有EventArgs.Empty.当然,我可能是愚蠢的,null而不是EventArgs.Empty在提出一些事件时,但在这里它将是一些自动生成的代码,将提升FormClosing事件,所以我只是抑制警告.
是否存在一些可能导致EventArgs被框架置空而不是由程序员引起的极端情况?
简答:是的,你可以这样做:
public void DoSomething()
{
OnFormClosing(null);
}
Run Code Online (Sandbox Code Playgroud)
但除非您实际执行此类操作,否则您可以忽略该警告.
查看类Form的源代码,我们可以找到这个方法,它继续这样:
/// <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;
}
Run Code Online (Sandbox Code Playgroud)
所以不,e当WinForms引发事件时,无法为null.