EventArgs可以为空吗?
本文关键字:EventArgs | 更新日期: 2023-09-27 17:53:51
我在一些代码中有protected override void OnFormClosing(FormClosingEventArgs e)
,代码分析给出CA1062,因为我不检查e
是否为空。
惯例是EventArgs
不应该为空;这就是为什么我们有EventArgs.Empty
。当然,我可以是愚蠢的,传递null
而不是EventArgs.Empty
时,引发一些事件,但这里将是一些自动生成的代码,将引发FormClosing事件,所以我只是抑制警告。
是否有一些角落的情况下,可能导致EventArgs是空的框架,而不是由程序员引起的?
简短的回答:是的,你可以这样做:
public void DoSomething()
{
OnFormClosing(null);
}
但是除非你真的这样做了,否则你可以忽略这个警告。
查看类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;
}
因此,当WinForms引发事件时,e
将不会为null。