C# 中的 == 与等于
C# 中 == 和 Equals 的计算有什么区别?
对于前,
if(x==x++)//Always returns true
但
if(x.Equals(x++))//Always returns false
已编辑:
int x=0;
int y=0;
if(x.Equals(y++))// Returns True
What is the difference between the evaluation of == and Equals in C#?
For Ex,
if(x==x++)//Always returns true
but
if(x.Equals(x++))//Always returns false
Edited:
int x=0;
int y=0;
if(x.Equals(y++))// Returns True
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据规范,这是预期的行为。
第一个的行为受规范第 7.3 节的约束:
因此,在
x==x++
中,首先计算左操作数 (0
),然后计算右操作数 (0
,>x
变为1
),然后比较完成:0 == 0
为 true。第二个的行为受第 7.5.5 节管辖:
请注意,值类型通过引用传递到它们自己的方法。
因此,在 x.Equals(x++) 中,首先评估目标(E 是变量 x),然后评估参数(
0,
x
变为1
),然后比较完成:x.Equals(0)
为 false。编辑:我还想赞扬 dtb 现已撤回的评论,该评论是在问题关闭时发布的。我认为他也说了同样的话,但由于评论长度的限制,他无法完全表达出来。
According to the specification, this is expected behavior.
The behavior of the first is governed by section 7.3 of the spec:
Thus in
x==x++
, first the left operand is evaluated (0
), then the right-hand is evaluated (0
,x
becomes1
), then the comparison is done:0 == 0
is true.The behavior of the second is governed by section 7.5.5:
Note that value types are passed by reference to their own methods.
Thus in
x.Equals(x++)
, first the target is evaluated (E isx
, a variable), then the arguments are evaluated (0
,x
becomes1
), then the comparison is done:x.Equals(0)
is false.EDIT: I also wanted to give credit to dtb's now-retracted comment, posted while the question was closed. I think he was saying the same thing, but with the length limitation on comments he wasn't able to express it fully.
评估顺序。 ++ 首先评估(第二个示例)。但在第一个示例中,== 首先执行。
Order of evaluation. ++ evaluates first (second example). But in the first example, == executes first.