简体   繁体   English

如何在C#中测试条件运算符的右关联性

[英]How to test the right-associativity of conditional operator in c#

I wrote the following code. 我写了下面的代码。

static void Main(string[] args)
{
    var xyz = 10 < 11 ? 12 : 5 < 21 ? getValue() : 15;
    Console.WriteLine(xyz);
    Console.ReadLine();
}

static int getValue()
{
    Console.WriteLine("hello");
    return 100;
}

Since the first condition is always true, the value that xyz will get is 12 but since the conditional operator is itself right associative, I was expecting that the getValue() function would be executed first and "hello" would be printed. 由于第一个条件始终为true,因此xyz将获得的值为12,但是由于条件运算符本身是正确的关联,因此我期望getValue()函数将首先执行,并且将输出“ hello”。 When I run this code, it doesn't run that way. 当我运行此代码时,它不会那样运行。

Can someone please enlighten me on this behavior. 有人可以启发我这种行为。

This: 这个:

var xyz = 10 < 11 ? 12 : 5 < 21 ? getValue() : 15;

is treated as: 被视为:

var xyz = 10 < 11 ? 12 : (5 < 21 ? getValue() : 15);

So we have a conditional expression with: 所以我们有一个条件表达式:

  • Condition: 10 < 11 条件: 10 < 11
  • First branch: 12 第一分支: 12
  • Second branch: 5 < 21 ? getValue() : 15 第二分支: 5 < 21 ? getValue() : 15 5 < 21 ? getValue() : 15

As 10 < 11 is true, the first branch is evaluated but the second branch is not. 由于10 < 11为真,因此评估第一个分支,但不评估。

The associativity isn't as easily shown with your code as with code which uses a bool expression for every operand - as that could compile with either associativity. 关联性不像在每个操作数中都使用bool表达式的代码那样容易地显示出来,因为可以使用两种关联性进行编译。

Consider this code: 考虑以下代码:

using System;

class Test
{
  static void Main()
  {            
    var xyz = Log(1, true) ? Log(2, true) : Log(3, true) ? Log(4, false) : Log(5, true);
  }

  static bool Log(int x, bool result)
  {
    Console.WriteLine(x);
    return result;
  }
}

Renaming each Log(x, ...) to Lx for simplicity, we have: 为了简单起见,将每个Log(x, ...)重命名为Lx ,我们有:

var xyz = L1 ? L2 : L3 ? L4 : L5;

That could be handled as: 可以这样处理:

// Right associativity
var xyz = L1 ? L2 : (L3 ? L4 : L5);

// Left associativity
var xyz = (L1 ? L2 : L3) ? L4 : L5;

Given the results we're returning, with right-associativity we'd expect to see output of 1, 2. With left-associativity, we'd see 1, 2, 4. The actual output is 1, 2, showing right-associativity. 给定我们要返回的结果,我们希望看到右结合性为1、2的输出。如果是左边结合性,我们将会看到1、2、4的实际输出。关联。

If you translate the code into in..else statement, it would be - 如果将代码转换为in..else语句,则它将是-

        int xyz = 0;
        if (10 < 11)
        {
            xyz = 12;
        }
        else
        {
            if (5 < 21)
            {
                xyz = getValue();
            }
            else
            {
                xyz = 15;
            }
        }

And since the first if condition evaluates to true, the else will not execute and you will get 12 printed on console. 并且由于第一个if条件评估为true,否则else将不会执行,您将在控制台上打印12。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM