简单而有趣的问题:
从下面的代码中,我想知道在两种情况下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.
输出:
有人可以简单地解释一下幕后发生的事情吗?
//在这两种情况下,C#编译器都将执行什么操作?
答案 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