我想试试下面的代码:
//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, 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.
...
所以我把它修改成这样:
if (m.terms[0] != null)
{
if (m.terms[0].labels != null)
{
if (m.terms[0].labels[0].title == "Part-of-speech") { result = true; }
}
}
这是最好的方法吗?
最佳答案
&&
是短路运算符,因此您编写的第一种方式和第二种方式在功能上是等效的。
if (a && b && c)
{
// work
}
b
只有在 a
返回 true 时才会被计算。 (同样适用于 c
)。
在您的代码中,检查 m.terms[0].labels
不会成为问题,因为如果 m.terms[0]
为空。
但是,为了完全覆盖您自己,您可能希望添加对 m
和 m.terms
的检查。
m != null && m.terms != null && m.terms.Count > 0 && m.terms[0] != null ...
当它从左到右计算时,它会在第一个不通过的条件下中断,其余的将不被检查。
关于c# - 关于 if 语句的更短代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6861181/