【问题标题】:Checking whether nested/hierarchy of properties are null?检查属性的嵌套/层次结构是否为空?
【发布时间】:2015-08-27 06:57:21
【问题描述】:

我有:

label.Text = myObject.myNestedObject.MyNestedObject2.Description;

其中 label 是 asp.net 标签。问题是有时 myObject、myNestedObject、MyNestedObject2 或 Description 为空,我必须在 if 语句中检查它,如下所示:

if(myObject!=null&&myNestedObject!=null&&MyNestedObject2!=null&&Description!=null)
{
label.Text = myObject.myNestedObject.MyNestedObject2.Description;
}

在这个语句中,我检查了四次属性是否为空。是否存在任何其他方法来检查整个层次结构?

【问题讨论】:

    标签: c# asp.net oop if-statement


    【解决方案1】:

    C# null-conditional operators 来救援!

    取自 MSDN 网站:

    int? length = customers?.Length; // null if customers is null 
    Customer first = customers?[0];  // null if customers is null
    int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null
    

    【讨论】:

    • 我认为这是 .net 框架的新版本的一个很好的答案,但我在我的项目中使用 .Net 4.5,不幸的是这个有用的选项不起作用。
    • 不幸的是,旧版语言中没有新的空条件运算符。请注意,.NET Framework 版本和语言 (C#) 版本之间存在巨大差异。您可以使用 VS2015 和较新的 C# 语言功能,但仍以 .NET 4.5 为目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2020-09-16
    • 1970-01-01
    相关资源
    最近更新 更多