【问题标题】:C# Null Conditional Operator inside method argument方法参数内的 C# Null 条件运算符
【发布时间】:2018-09-22 11:52:33
【问题描述】:

我有以下方法:

float myMethod(MyObject[][] myList) 
{
      float a = 0;
      if (myListProcessingMethod(myList?.Where(x => x.mySatisfiedCondition()).ToList()))
      {
            a = 5;
      }
      return a;
}

bool myListProcessingMethod(List<MyObject[]> myList)
{
      bool isSuccess = false;
      if (myList.Any())
      {
            isSuccess = true;
      }
      return isSuccess;
}

我认为这种情况:

if (myListProcessingMethod(myList?.Where(x => x.mySatisfiedCondition()).ToList()))

我将我的条件重构为:

if (myList?.Length != 0)
{
      if (myListProcessingMethod(myList.Where(x => x.mySatisfiedCondition()).ToList()))
      {
            a = 5;
      }
}

这两个条件是等价的吗?以传统方式与第一个 NullConditionOperator 等效的条件是什么?与使用 NullConditionalOperator 进行第二次传统检查的等效条件是什么?

【问题讨论】:

  • List&lt;T&gt; 没有 Length 属性。你的意思是Count?你能提供一个minimal reproducible example 并先自己测试代码吗?请注意,如果myList 为空,myList?.Count 为空,不等于 0 - 所以你最终会出现异常。
  • myListProcessingMethod() 基本上可以归结为return myList.Any();
  • 我编辑我的问题:实际上我在第一个方法参数中有一个二维对象数组
  • 你为什么不直接说if (myList?.Any(x =&gt; x.satisfiesCondition()) ?? false) { a = 5; }

标签: c# short-circuiting null-conditional-operator


【解决方案1】:

下面的语句可能会崩溃。如果myList 为空,myList?.Length 将为空,myList?.Length != 0 将为true。这意味着myList.Where 可能会因空引用异常而崩溃。

if (myList?.Length != 0)
{
  if (myListProcessingMethod(myList.Where(x => x.mySatisfiedCondition()).ToList()))
  {
        a = 5;
  }
}

你可能想要

if (myList?.Length > 0) 
...

仅当列表不为 null 且其长度大于 0 时才会评估为 true

【讨论】:

  • 也许他不使用System.Collection.Generic.List。你错过了@Badiparmagi这一点
  • @Andrew 是否可以将这两个 if 语句作为 myListProcessingMethod 参数加入?
  • @ElConrado 您可以使用 &amp;&amp; 而不是 2 ifs... 或者您是什么意思?您还可以使 myListProcessingMethod 成为扩展方法,以便在最后链接它,在 ToList 之后。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 2020-11-25
  • 2016-09-07
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 2015-03-28
相关资源
最近更新 更多