【发布时间】: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<T>没有Length属性。你的意思是Count?你能提供一个minimal reproducible example 并先自己测试代码吗?请注意,如果myList为空,myList?.Count为空,不等于 0 - 所以你最终会出现异常。 -
myListProcessingMethod() 基本上可以归结为
return myList.Any();。 -
我编辑我的问题:实际上我在第一个方法参数中有一个二维对象数组
-
你为什么不直接说
if (myList?.Any(x => x.satisfiesCondition()) ?? false) { a = 5; }?
标签: c# short-circuiting null-conditional-operator