[英]Can EventArgs ever be null?
I have protected override void OnFormClosing(FormClosingEventArgs e)
in some of my code and code analysis gives a CA1062 because I don't check if e
is null. 我在某些代码中
protected override void OnFormClosing(FormClosingEventArgs e)
,并且代码分析给出了CA1062,因为我不检查e
是否为null。
Convention is that EventArgs
should never be null; 约定
EventArgs
永远不应为null; that's why we have EventArgs.Empty
. 这就是为什么我们有
EventArgs.Empty
的原因。 Sure, I could be stupid and pass null
instead of EventArgs.Empty
when raising some event, but here it will be some auto-generated code that will be raising the FormClosing event so I just suppressed the warning. 当然,我可能很愚蠢,并在引发某些事件时传递
null
而不是EventArgs.Empty
,但是这里将使用一些自动生成的代码引发FormClosing事件,因此我只是取消了警告。
Are there some corner cases that could cause EventArgs to be null by the framework and not caused by the programmer? 是否有一些极端情况可能导致EventArgs由框架为null而不是由程序员引起的?
Short answer: yes, you can do this: 简短的回答:是的,您可以这样做:
public void DoSomething()
{
OnFormClosing(null);
}
But unless you actually do something like this, you can ignore the warning. 但是,除非您实际执行此类操作,否则可以忽略该警告。
Looking at the source code for class Form, we can find this method , which resumes to this: 查看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;
}
So no, there is no way e
will be null when the event is raised by WinForms. 所以不,当WinForms引发事件时,
e
不可能为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.