c# - 关于 if 语句的更短代码

标签 c# if-statement

我想试试下面的代码:

//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] 为空。

但是,为了完全覆盖您自己,您可能希望添加对 mm.terms 的检查。

m != null && m.terms != null && m.terms.Count > 0 && m.terms[0] != null ...

当它从左到右计算时,它会在第一个不通过的条件下中断,其余的将不被检查。

关于c# - 关于 if 语句的更短代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6861181/

相关文章:

c# - 在 Entity Framework 中将 tinyint 字段表示为枚举

sql-server - SQL动态查询: check whether table column has any data

javascript - 数据列表和结果重定向有问题

c# - 重载方法以支持引用类型和可空类型

c# - 调用多态类字段事件

c# - 我是否必须派生自 ConfigurationSection 以支持每个用户的设置?

c# - 禁用在 Visual Studio 2017 中不起作用的 Azure Functions 属性

c - 即使在 c 程序中条件失败后,if() 仍在执行

javascript - 递归函数打破if语句javascript

javascript - 检查 if 语句中的两个条件,即使第一个条件为假