我想不出更好的标题,但这个错误花了我很长时间才找到。
有人可以向我解释为什么这给了我不同的输出吗?
string may = "May";
string june = "June";
string july = "July";
Console.WriteLine(may?.Length ?? 0 + june?.Length ?? 0 + july?.Length ?? 0) ;
Console.WriteLine(may == null ? 0 : may.Length + june == null ? 0 : june.Length + july == null ? 0 : july.Length) ;
Console.WriteLine( (may == null ? 0 : may.Length) + (june == null ? 0 : june.Length) + (july == null ? 0 : july.Length)) ;
我已经跨过它,在我的脑海中,我只是无法弄清楚到底发生了什么。 这里的评估顺序是什么?
我希望字符串零合并逻辑或三元逻辑是这样的(顺便说一句!
int tempRes = 0;
tempRes+=may == null ? 0 : may.Length;
tempRes+=june == null ? 0 : june.Length;
tempRes+=july == null ? 0 : july.Length;
Console.WriteLine(tempRes);
与其说是计算顺序,不如说是运算符优先级。
may?.Length ?? 0 + june?.Length ?? 0 + july?.Length ?? 0
这意味着:
may?.Length ?? (0 + june?.Length) ?? (0 + july?.Length) ?? 0
这显然不是你想要的。你想要的可以表达为
(may?.Length ?? 0) + (june?.Length ?? 0) + (july?.Length ?? 0)
同样
may == null ? 0 : may.Length + june == null ? 0 : june.Length + july == null ? 0 : july.Length
意味着
may == null ? 0 : ((may.Length + june) == null ? 0 : ((june.Length + july) == null ? 0 : july.Length))