多个三元运算符并将 int 评估为布尔神秘

Multiple ternary operators and evaluating int as boolean mystery

int cow;
int cow = true ? false ? false ? false ? 3 : 4 : 5 : 6 : 7;

这个三元运算符是如何工作的?

为什么它给我它给我的结果?

问的人已经很清楚了。请给我更多的声誉减分。

如果您删除了所有无法访问的代码,您最终会得到

cow = true ? 6 : 7;

6每次都会是你的答案。

顺便说一句,你的问题是什么?

Why does any combination of true and false return the value it does?

这里没有任何布尔值的组合。此 ?: operator returns 第一个或第二个表达式,不是条件本身

condition ? first_expression : second_expression;

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result.

由于此运算符是 right-associative,您的代码相当于;

true ? false ? false ? false ? 3 : 4 : 5 : 6 : 7

评价为;

true ? false ? false ? (false ? 3 : 4) : 5 : 6 : 7

评估为;

true ? false ? false ? 4 : 5 : 6 : 7

评估为;

true ? false ? (false ? 4 : 5) : 6 : 7

评估为;

true ? false ? 5 : 6 : 7

评估为;

true ? (false ? 5 : 6) : 7

评估为;

true ? 6 : 7

其中 returns 6.

C# 三元运算符是 if 语句的语法糖。

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

https://msdn.microsoft.com/en-us/library/ty67wk28.aspx?f=255&MSPPError=-2147217396

这是不使用三元的等效代码。总会掉到牛=6块。

        if (true)
        {
            if (false)
            {
                if (false)
                {
                    if (false)
                    {
                        cow = 3;
                    }
                    else
                    {
                        cow = 4;
                    }
                }
                else
                {
                    cow = 5;
                }
            }
            else
            {
                cow = 6;
            }
        }
        else
        {
            cow = 7;
        }