关于 if 语句的更短代码
我想尝试以下代码:
//all arrays are List<T> type.
if (m.terms[0] != null && m.terms[0].labels != null && m.terms[0].labels[0].title == "Part-of-speech")
{
result = true;
}
但在以下情况下偶尔会出现运行时错误
i. m.terms == null
ii. m.terms != null,但 m.terms[0] 未初始化。
iii. m.terms != null, 并且 m.terms[0] 已经存在但是 m.terms[0].label 未初始化。
...
所以我确实将其修改为这样:
if (m.terms[0] != null)
{
if (m.terms[0].labels != null)
{
if (m.terms[0].labels[0].title == "Part-of-speech") { result = true; }
}
}
这是最好的方法吗?
i wanted to try the following code:
//all arrays are List<T> type.
if (m.terms[0] != null && m.terms[0].labels != null && m.terms[0].labels[0].title == "Part-of-speech")
{
result = true;
}
but it occured runtime error occasionly in following situation
i. m.terms == null
ii. m.terms != null, but m.terms[0] does not intialized.
iii. m.terms != null, and m.terms[0] has been exist but
m.terms[0].label does not initialized.
...
so i did modify it to like this:
if (m.terms[0] != null)
{
if (m.terms[0].labels != null)
{
if (m.terms[0].labels[0].title == "Part-of-speech") { result = true; }
}
}
is it the best way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这都是关于可读性的。 C# 使用短路评估,因此在功能上没有区别。
This is all about readability. C# uses Short-circuit evaluation so in functionality there is no difference.
试试这个
try this
是的,最好将每个 null 检查分成单独的 if 语句。
原因是第二个和第三个条件要求第一个条件不为空。如果第一个条件为空,那么第二个和第三个条件将依次抛出错误,因为它们的父条件为空但正在尝试访问。
Yes, it would be better to split off each null check into a separate if statement.
The reason is that the second and third conditions require the first to not be null. If the first is null, then the second and third conditions will in turn throw errors because their parent is null yet is trying to be accessed.
&&
是一个短路运算符,因此您编写的第一种方式和第二种方式在功能上是等效的。仅当
a
返回 true 时才会评估b
。 (c
也是如此)。在您的代码中,检查
m.terms[0].labels
不会出现问题,因为 ifm.terms[0]
会导致表达式短路已经为空。但是,为了完全覆盖自己,您可能需要添加对
m
和m.terms
的检查。当它从左到右评估时,它将在第一个不通过的条件下中断,其余的将不受检查。
&&
is a short circuiting operator, so the first way you wrote it and the second way will be functionally equivalent.b
will only be evaluated ifa
returns true. (Same goes forc
).In your code, checking
m.terms[0].labels
will not be a problem because you would have short-circuited out of the expression ifm.terms[0]
had been null.To completely cover yourself, you'd want to possibly add checks for
m
andm.terms
, however.As it evaluates from left to right, it will break on the first condition that doesn't pass and the rest will go unchecked.