C# Null 传播运算符/条件访问表达式 &如果块

时间:2022-11-04
本文介绍了C# Null 传播运算符/条件访问表达式 &如果块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

空传播运算符/条件访问表达式tagged/c%23-6.0" class="post-tag" title="show questions tagged 'c#-6.0'" rel="tag">c#-6.0 看起来非常方便.但我很好奇它是否有助于解决检查子成员是否为空然后在 if 块内对所述子成员调用布尔方法的问题:

The Null propagating operator / Conditional access expression coming in c#-6.0 looks like quite a handy feature. But I'm curious if it will help solve the problem of checking if a child member is not null and then calling a Boolean method on said child member inside an if block:

  public class Container<int>{
       IEnumerable<int> Objects {get;set;}
  }

  public Container BuildContainer()
  { 
      var c = new Container();

      if (/* Some Random Condition */)
         c.Objects = new List<int>{1,2,4};
  }

  public void Test()
  {
      var c = BuildContainer();

      //Old way
      if ( null != c && null != c.Objects && c.Objects.Any())
         Console.Write("Container has items!");


      //C# 6 way?
      if (c?.Object?.Any())
          Console.Write("Container has items!");
  }

c?.Object?.Any() 会编译吗?如果传播运算符短路(我认为这是正确的术语)为空,那么您有 if (null),这是无效的.

Will c?.Object?.Any() compile? If the propagating operator short circuits (I assume that's the right term) to null then you have if (null), which isn't valid.

C# 团队会解决这个问题还是我错过了空传播运算符的预期用例?

Will the C# team address this concern or am I missing the intended use case for the null propagating operator?

推荐答案

这样不行.您可以跳过解释并查看下面的代码:)

It won't work this way. You can just skip the explanation and see the code below :)

如您所知 ?. 如果子成员为 null,运算符将返回 null.但是如果我们尝试获取一个不可为空的成员,比如 Any() 方法,它返回 bool 会发生什么?答案是编译器会将返回值包装"在 Nullable<> 中.例如,Object?.Any() 会给我们 bool?(即 Nullable),而不是 bool.

As you know ?. operator will return null if a child member is null. But what happens if we try to get a non-nullable member, like the Any() method, that returns bool? The answer is that the compiler will "wrap" a return value in Nullable<>. For example, Object?.Any() will give us bool? (which is Nullable<bool>), not bool.

唯一不允许我们在 if 语句中使用这个表达式的是它不能被隐式转换为 bool.但是您可以明确地进行比较,我更喜欢像这样与 true 进行比较:

The only thing that doesn't let us use this expression in the if statement is that it can't be implicitly casted to bool. But you can do comparison explicitly, I prefer comparing to true like this:

if (c?.Object?.Any() == true)
    Console.Write("Container has items!");

感谢@DaveSexton 还有另一种方式:

if (c?.Object?.Any() ?? false)
    Console.Write("Container has items!");

但对我来说,与 true 的比较似乎更自然:)

But as for me, comparison to true seems more natural :)

这篇关于C# Null 传播运算符/条件访问表达式 &amp;如果块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!