代码之家  ›  专栏  ›  技术社区  ›  SwiftedMind

阅读许多元素-如何避免(…!=null)混乱?(嵌套)

  •  0
  • SwiftedMind  · 技术社区  · 7 年前

    我正在C#项目中使用Microsoft Linq读取xml文件。我从xml文档中访问数据的方式如下:

    document.Root.Element("myElement").Attribute("myAttribute").Value
    

    我收到警告,这可能会导致 NullReferenceException .我得检查一下 null )(对于我要读取的每个元素和属性)。

    但是,我不希望有很多嵌套的if检查,例如:

     if (... != null) {
        if (... != null) {
           if (... != null) {
              if (... != null) {
                 if (... != null) {
                     ...
                 }
              }
           }
        }
     }
    

    这很快就会变丑。有更好的方法进去吗 C# ?在里面 Swift ,有一种叫做 guard statement ,在这种情况下,这将是理想的。它还允许“强制展开”这些内容,这会告诉编译器这不能为null。C中是否有等价物?

    非常感谢。

    3 回复  |  直到 7 年前
        1
  •  7
  •   dymanoid    7 年前

    你听说了吗 null-conditional (or null-propagation) operator ? ?
    你可以这样写:

    var v = document.Root?.Element("myElement")?.Attribute("myAttribute")?.Value;
    

    所以如果 Root null Element("myElement") 退货 无效的 Attribute("myAttribute") 退货 无效的 ,结果将是 无效的

        2
  •  0
  •   Anton Tsches    7 年前

    为了避免这种连锁,我通常使用这种模式:

    if(... == null)
        break; // or continue; // or return; // depends on the context
    if(... == null)
        break; // or continue; // or return; // depends on the context
    ...
    

    这会将此链分解为一系列空检查

        3
  •  -1
  •   MatKai    7 年前

    您可以使用

    if( ... !=null && ...!=null && ...!=null...)
    

    或尝试捕捉 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch