C#编译中到底发生了什么?

时间:2018-12-19 17:18:10

标签: c# console-application puzzle

简单而有趣的问题:

从下面的代码中,我想知道在两种情况下Check变量都将是true,但是我错了。

using System;
namespace Problem
{
    class Program
    {
        static void Main(string[] args)
        {
            int firstNumber = 1;
            int secondNumber = 9;

            bool Check = false;

            Console.WriteLine("Checking First Condition.");
            Console.WriteLine("------------------");
            if (firstNumber == (firstNumber = secondNumber))
            {
                Check = true;
                Console.WriteLine("First Check : {0}", Check);
            }
            else
            {
                Check = false;
                Console.WriteLine("First Check : {0}", Check);
            }

             Console.WriteLine("------------------");
             Console.WriteLine();
             Console.WriteLine("Checking Second Condition.");
             Console.WriteLine("------------------");

            // Resetting firstNumber value:
            firstNumber = 1;

            if ((firstNumber = secondNumber) == firstNumber)
            {
                Check = true;
                Console.WriteLine("Second Check : {0}", Check);
            }
            else
            {
                Check = false;
                Console.WriteLine("Second Check : {0}", Check);
            }
            Console.WriteLine("------------------");
        }
    }
}

但是从不久前开始思考。 但我不明白为什么第一个条件返回True

空运行:

第一个条件。 (1 == (1 = 9) // firstnumber = 9. so 9 == 9 // True.

第二个条件。 ((1 = 9) == 1) // firstnumber = 9. so 9 == 9 // True.

输出:

enter image description here

有人可以简单地解释一下幕后发生的事情吗?

//在这两种情况下,C#编译器都将执行什么操作?

1 个答案:

答案 0 :(得分:4)

条件/表达式从左到右评估。所以,

 int firstNumber = 1;
 int secondNumber = 3;

第一种情况:

firstNumber == (firstNumber = secondNumber)
     1      == (firstNumber = secondNumber)
     1      == (     1      = secondNumber)
     1      == (     1      =      3      )
     1      ==   3
          false

第二种情况:

((firstNumber = secondNumber) == firstNumber)

 (     1      = secondNumber) == firstNumber
 (     1      =      3      ) == firstNumber   
 (            3             ) == firstNumber   //firstNumber became 3
              3               ==     3 
                             true