简体   繁体   English

在 C# 编译中发生了什么?

[英]What is going on Under the hood in C# Compilation?

Simple and Very Intersting Problem:简单且非常有趣的问题:

From the below Code, I was wondering that In both conditions the Check variable will be true but i was wrong.从下面的代码中,我想知道在这两种情况下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("------------------");
        }
    }
}

But from while ago and thinking about it.但从前不久开始思考。 but i can't get it why the first condition returning True但我不明白为什么第一个条件返回True

Dry Runs:试运行:

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

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

Output:输出:

在此处输入图片说明

Can someone explain breifly what is happening under the hood ?有人可以简要解释一下幕后发生的事情吗?

// What is done by a C# Compiler in both the cases ?. // 在这两种情况下,C# 编译器都做了什么?

conditions/expressions are evaluated from left to right.条件/表达式从左到右计算。 so,所以,

 int firstNumber = 1;
 int secondNumber = 3;

First Case:第一种情况:

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

Second Case:第二种情况:

((firstNumber = secondNumber) == firstNumber)

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

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

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