我想尝试以下代码:
//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没有被弱化。 iii. m.terms != null,m.terms已经存在,但是m.terms.label没有初始化。
..。
所以我把它修改成这样:
if (m.terms[0] != null)
{
if (m.terms[0].labels != null)
{
if (m.terms[0].labels[0].title == "Part-of-speech") { result = true; }
}
}
这是最好的方法吗?
发布于 2011-07-28 15:07:10
&&
是一个短路运算符,所以您编写它的第一种方式和第二种方式在功能上是等价的。
if (a && b && c)
{
// work
}
只有当b
返回true时,才会对a
进行评估。(c
也是如此)。
在您的代码中,检查m.terms[0].labels
不会有问题,因为如果m.terms[0]
为null,那么表达式就会短路。
但是,为了完全覆盖您自己,您可能希望添加m
和m.terms
检查。
m != null && m.terms != null && m.terms.Count > 0 && m.terms[0] != null ...
当它从左到右计算时,它将在第一个不通过的条件下中断,其余的将不受检查。
发布于 2011-07-28 15:07:04
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;
}
}
}
发布于 2011-07-28 15:07:42
这都是关于可读性的。C#使用短路评估,因此在功能上没有区别。
https://stackoverflow.com/questions/6861181
复制相似问题