== VS等于C# [英] == vs Equals in C#
问题描述
是什么==评价之间的差异,在C#等于?
有关防爆,
如果(X == X ++)//始终返回true,
但
如果(x.Equals(X ++))//始终返回false
编辑:
INT X = 0;
INT Y = 0;
如果(x.Equals(Y ++))//返回True
根据规范,这是预期的行为。
第一次的行为是规范的7.3节管辖。
<在表达式块引用>
操作数从左至右进行评价。例如,在 F(I)+ G(我+ +)* H(I)
,方法F使用我的旧值被调用,那么方法G称为与我的旧值,并且,最后,方法H称为与i的新值。在这是独立且无运算符优先级。
块引用>
因此Y == X ++ ,第一左操作数进行评估( 0
),然后右手被评估( 0
, X
变成 1
),则比较完成: 0 == 0 $ C 。$ C>是真的
第二的行为是由部分7.5.5决定:
- 如果M是在的值类型中声明的实例函数成员的:
- E是评估。如果此计算导致异常,则不执行进一步的操作。
- 如果E没有被归类为一个变量,那么E同类型的临时局部变量被创建和E的值分配给该变量。则E被重新归类为对该临时局部变量的引用。临时变量是如此访问内男,但不以任何其他方式。因此,只有当E是一个真正的变量是有可能调用者观察到M对this所做的更改。
- 参数清单中的第7.5.1节所述进行评价。
- M被调用。 E引用的变量成为this引用的变量。
块引用>
注意值类型参照以自己的方式通过。
因此,在
X。等于(X ++)
,第一个目标是评估(E是X
,一个变量),那么参数计算(0
,X
变成1
),则比较完成:<$ C 。$ C> x.Equals(0)为假
编辑:我也想给信贷DTB现在缩回评论,张贴而这个问题被关闭。我想他是在说同样的事情,但对注释的长度限制他不能够完全表达出来。
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
解决方案According to the specification, this is expected behavior.
The behavior of the first is governed by section 7.3 of the spec:
Operands in an expression are evaluated from left to right. For example, in
F(i) + G(i++) * H(i)
, method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.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:
- If M is an instance function member declared in a value-type:
- E is evaluated. If this evaluation causes an exception, then no further steps are executed.
- If E is not classified as a variable, then a temporary local variable of E’s type is created and the value of E is assigned to that variable. E is then reclassified as a reference to that temporary local variable. The temporary variable is accessible as this within M, but not in any other way. Thus, only when E is a true variable is it possible for the caller to observe the changes that M makes to this.
- The argument list is evaluated as described in §7.5.1.
- M is invoked. The variable referenced by E becomes the variable referenced by this.
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.
这篇关于== VS等于C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!