方法参数内的C#空条件运算符

我有以下方法:


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进行第二次传统检查的等效条件是什么?


阿晨1998
浏览 129回答 1
1回答

Cats萌萌

下面的语句可能会崩溃。如果myList为null,myList?.Length则将为null,并且myList?.Length != 0将为true。这意味着myList.Where可能会因空引用异常而崩溃。if (myList?.Length != 0){&nbsp; if (myListProcessingMethod(myList.Where(x => x.mySatisfiedCondition()).ToList()))&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; a = 5;&nbsp; }}你可能想要if (myList?.Length > 0)&nbsp;...仅当列表不为null且其Length大于0时,它的评估结果才为true。
打开App,查看更多内容
随时随地看视频慕课网APP