问题是:如果您对这个问题很清楚,请向我解释我没有看到什么。我的问题是:三元实际上是如何工作的?澄清我的问题:从右到左的关联性在这里真正意味着什么?为什么关联性与评估顺序不同?这显然就像一个 if else 语句。它不是从右到左评估的。在我看来是从左到右的联想。
我做了布尔值来尝试证明这一点。它告诉我它不是右联想。(我可能不明白右联想的含义。)如果它是右联想,它会像这样工作,这是给我的答案:
“由于此运算符是右关联的,因此您的代码可以用作;”
true ? false ? false ? false ? 3 : 4 : 5 : 6 : 7
evaluated as;
true ? false ? false ? (false ? 3 : 4) : 5 : 6 : 7
which evaluated as;
true ? false ? false ? 4 : 5 : 6 : 7
which evaluated as;
true ? false ? (false ? 4 : 5) : 6 : 7
which evaluated as;
true ? false ? 5 : 6 : 7
which evaluated as;
true ? (false ? 5 : 6) : 7
which evaluated as;
true ? 6 : 7
which returns 6.
我试图证明这一点,如下所示:
int Proof = ternaryTrueOne() ? ternaryTrueTwo() ? ternaryFalseOne() ?
ternaryTrueThree() ? ternaryFalseTwo() ? 2 : 3 : 4 : 5 : 6 : 7;
static bool ternaryTrueOne()
{
Console.WriteLine("This is ternaryTrueOne");
return true;
}
static bool ternaryTrueTwo()
{
Console.WriteLine("This is ternaryTrueTwo");
return true;
}
static bool ternaryTrueThree()
{
Console.WriteLine("This is ternaryTrueThree");
return true;
}
static bool ternaryFalseOne()
{
Console.WriteLine("This is ternaryFalse");
return false;
}
static bool ternaryFalseTwo()
{
Console.WriteLine("This is ternaryFalseTwo");
return false;
}
在这种情况下,这将以相同的方式进行评估。正确的?这意味着 ternaryfalsetwo 将首先写入控制台。但它没有。它根本不写。它实际上是这样工作的,并且我将三元表达式编写为 if 语句。它从左到右工作,并且不必评估其余代码。在第一个错误语句之后,所有其他语句都无法访问。
private static int Proof2()
{
if (ternaryTrueOne())
{
if (ternaryTrueTwo())
{
if (ternaryFalseOne())
{
if (ternaryTrueThree())
{
if (ternaryFalseTwo())
{
return 6;
}
else
{
return 7;
}
return 5;
}
else
{
return 6;
}
return 4;
}
else
{
return 5;
}
return 3;
}
else
{
return 4;
}
return 2;
}
else
{
return 3;
}
}
原来的答案错了吗?正确的关联性到底意味着什么?