C#——我们应该检查 lambda 中的传入参数吗?
我们应该检查 lambda 表达式的传入参数吗? 换句话说,我们应该检查参数o和s吗?
class MainWindow : Form /// implementation I
{
...
private ToolStripMenuItem mnuFileExit = new ToolStripMenuItem();
private void BuildMenus()
{
...
mnuFileExit.Click += (o, s) =>
{
MessageBox.Show(string.Format("{0} sent this event", o.ToString()));
Application.Exit();
};
...
}
...
}
class MainWindow : Form /// implementation II
{
...
private ToolStripMenuItem mnuFileExit = new ToolStripMenuItem();
private void BuildMenus()
{
...
mnuFileExit.Click += (o, s) =>
{
if (o != null)
{
MessageBox.Show(string.Format("{0} sent this event", o.ToString()));
Application.Exit();
}
};
...
}
...
}
Should we check pass-in parameters of the lambda expression?
In other words, should we check the parameter o and s?
class MainWindow : Form /// implementation I
{
...
private ToolStripMenuItem mnuFileExit = new ToolStripMenuItem();
private void BuildMenus()
{
...
mnuFileExit.Click += (o, s) =>
{
MessageBox.Show(string.Format("{0} sent this event", o.ToString()));
Application.Exit();
};
...
}
...
}
class MainWindow : Form /// implementation II
{
...
private ToolStripMenuItem mnuFileExit = new ToolStripMenuItem();
private void BuildMenus()
{
...
mnuFileExit.Click += (o, s) =>
{
if (o != null)
{
MessageBox.Show(string.Format("{0} sent this event", o.ToString()));
Application.Exit();
}
};
...
}
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需检查第一个参数是否为空;因为它是发送者并且始终不为空。
我不同意参数名称的选择(
o
和s
)。通常,第一个参数名为s
(对于发送者),第二个参数名为e
(对于事件)。No need to check that the 1st parameter is null; because it is the sender and is always non-null.
I disagree with the choice of argument names (
o
ands
). Normally the first parameter is nameds
(for sender) and the second parameter is namede
(for event).您不必向发送者 (o) 添加空检查,因为它是事件发送者。它是 mnuFileExit ,它不会为空。
You don't have to add null check to the sender (o) as it is the event sender. It is mnuFileExit which wouldn't be null.