关于if语句的更多简短代码
本文关键字:代码 if 语句 关于 | 更新日期: 2023-09-27 18:04:04
我想试试下面的代码:
//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;
}
但在下列情况下偶尔发生运行时错误
。 m.terms == null
二世。 m.terms != null,但m.terms[0]没有初始化。
iii。 m.terms != null,并且m.terms[0]已经存在,但是m.terms[0]。标签未初始化
…
所以我把它修改成这样:
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 ...
从左到右计算时,如果第一个条件不满足,它将中断,其余条件不检查
int index = 0;
int labelIndex = 0;
string titleToCheck = "Part-of-speech";
if (m != null && m.terms != null && m.terms.Count > index)// or m.Length...
{
if (m.terms[index] != null && m.terms[index].labels != null &&
m.terms[index].labels.Count > labelIndex)
{
if (m.terms[index].labels[labelIndex].title == titleToCheck)
{
result = true;
}
}
}
这都是关于可读性的。c#使用Short-circuit求值,所以在功能上没有区别。
try this
if (m!=null && m.terms!= null && m.terms[0].labels!=null && m.terms[0].labels[0].title!=null && m.terms[0].labels[0].title == "Part-of-speech")
是的,最好将每个空检查分离到单独的if语句中。
原因是第二个和第三个条件要求第一个条件不为空。如果第一个条件为空,那么第二个和第三个条件又会抛出错误,因为它们的父条件为空,但仍在尝试访问。