C#空传播运营商/条件访问表达式和放大器;如果块 [英] C# Null propagating operator / Conditional access expression & if blocks

查看:177
本文介绍了C#空传播运营商/条件访问表达式和放大器;如果块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助空传播运营商/条件接收表达中的标签'C#-6.0'的rel =标签> -6.0级=标签后称号=节目的问题看起来像一个非常方便的功能。不过我很好奇,如果这将有助于解决检查,如果一个子成员不为空,然后调用的布尔方法的问题上表示,内部的子成员如果块:

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?。任何() 编译?如果经营者传播短路(我认为这是正确的术语)为空值,那么你必须如果(空),这是无效的。

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?如果一个子成员为空。但是,如果我们试图得到一个非空的成员,如任何()方法,返回布尔会发生什么?答案是,编译器将包装一回在可空LT值&;> 。例如,对象?。任何()会给我们布尔?(这是可空< ;布尔> ),而不是布尔

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 在这个表达式语句是它不能隐式强制转换为布尔。但你可以做的比较明确的,我喜欢比较真正是这样的:

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!");



至于我,比较真正似乎更自然:)

这篇关于C#空传播运营商/条件访问表达式和放大器;如果块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆