[英]C# Console.WriteLine Weird
Here is a simple script in C# which outputs two different things. 这是C#中的一个简单脚本,它输出两个不同的东西。 The issue is not about comparing the objects - don't get misguided. 问题不在于比较对象-不要被误导。 This is about using Console.WriteLine
to send an output. 这是关于使用Console.WriteLine
发送输出。
var a = "hello";
var b = string.Copy(a);
Console.WriteLine($"a == b: {a == b}");
Console.WriteLine("a == b:" + a == b);
The first Console.WriteLine
outputs a == b: True
and the second one outputs False
which means ignoring the part in the quotation ( "a == b:"
). 第一个Console.WriteLine
输出a == b: True
,第二个Console.WriteLine
输出False
,这意味着忽略引号中的部分( "a == b:"
)。
I am using VS 2015 and C# 4.5.2 - tested with 4.6 still the same result. 我正在使用VS 2015和C#4.5.2-用4.6测试仍然是相同的结果。
Any idea about this behavior highly appreciated. 任何对此行为的想法高度赞赏。
The ==
operator has a lower precedence than the +
operator. ==
运算符的优先级低于+
运算符。 That means that first "a == b:"
is concatenated( +
) with a
and then the result is compared( ==
) with b
which returns False
. 这意味着首先将"a == b:"
与a
串联( +
),然后将结果与b
进行比较( ==
),并返回False
。
See: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/ 请参阅: https : //docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/operators/
Additive operators are higher than equality operators, so they have a higher precedence . 可加运算符比等式运算符高,因此它们的优先级更高。
You could force it with ()
, in the following code a == b
is evaluated first: 您可以使用()
强制使用它,在下面的代码中,首先对a == b
求值:
Console.WriteLine("a == b:" + (a == b));
Your first example is using string interpolation where the whole expression is evaluated before ToString
is called and then the result is concatenated with the rest. 您的第一个示例使用字符串插值,其中在调用ToString
之前先对整个表达式求值,然后将结果与其余值连接在一起。
The second line is evaluating: 第二行正在评估:
"a == b:" + a == b
And correctly returning False. 并正确返回False。 IE IE浏览器
( "a == b:" + a ) == b
So the string is being built as a == b:hello' and being compared to 'hello' as the
+ operation is done before the
==` 因此,将字符串构建为a == b:hello' and being compared to 'hello' as the
+ operation is done before the
==` operation is done before the
You can resolve this by putting brackets around the a == b
您可以通过在方括号a == b
周围解决此问题
Console.WriteLine("a == b:" + (a == b));
Your second line is 'string literal + a' == b, which will be false. 您的第二行是'字符串文字+ a'== b,这将是错误的。 In essence you are doing 本质上你在做
"a == b:hello" == b
Which is always going to return false. 总是会返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.