为什么下面的代码返回false?C#coalesce运算符
public static void Main()
{
bool? someCondition = true;
bool someConditionOverride = false;
bool? result = someCondition ?? someConditionOverride ? false : (bool?)null;
Console.WriteLine(result);
}
我exprecting结果将是true
,因为someCondition
不null
和??
运营商将返回true
。不过看起来像右边的操作数是先计算出来的,左边的部分是简单的忽略。
添加括号解决困惑:
bool? result = someCondition ?? (someConditionOverride ? false : (bool?)null)
而结果将是true
。不过,我仍然很好奇为什么左边的部分在第一个例子中被忽略了。
[C#空合并(??)运算符的运算符优先级是什么?](https://stackoverflow.com/questions/511093/what-is-the-operator-precedence-of-c-sharp- null-coalescing-operator)解释它......可能可以用作重复。 –
这实际上是一个非常好的问题 –
只需读取我期望首先评估的'''表达式,从而导致'false'返回。我不希望'?:'具有更高的优先级,就像我不希望'+'优先于'-' –