更新时间:2023-02-01 21:39:59
您的问题是,你错过了 i.Equals(J)的隐式转换
。它进入到超载 int.Equals(INT)
。在这里,我们比较我
和(INT)Ĵ
,这是同样的事情。同样的隐式转换会发生在 ==
。
其他的比较上工作的 INT
和为sbyte
,它通过定义不同。 j.Equals(我)
进入过载 int.Equals(对象)
,因为参数不是隐转换为为sbyte
。
等于
是对称的他们,但是你的电话code不是。如果你想喝preSS隐式转换为 i.Equals((对象)j)条
,它会返回假
,显示等于
的确是对称的。
After reading this question Why do "int" and "sbyte" GetHashCode functions generate different values? I wanted to dig further and found following behavior:
sbyte i = 1;
int j = 1;
object.Equals(i, j) //false (1)
object.Equals(j, i) //false (2)
i.Equals(j) //false (3)
j.Equals(i) //true (4)
i == j //true (5)
j == i //true (6)
i.GetHashCode() == j.GetHashCode() //false (7)
If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result. This means that if objA overrides the Object.Equals(Object) method, this override is called.
I'm very interested if anyone can explain why such in my opinion inconsistent behaviour is observed in rather fundamental .NET types.
Your problem is that you missed the implicit conversion in i.Equals(j)
. It goes to the overload int.Equals(int)
. Here you're comparing i
and (int)j
, which are the same thing. The same implicit conversion happens for ==
.
The other comparisons work on an int
and a sbyte
, which by definition are different. j.Equals(i)
goes to the overload int.Equals(object)
, because the argument isn't implicitly convertible to sbyte
.
Equals
is symmetric for them, but your calling code isn't. If you suppress the implicit conversion with i.Equals((object)j)
, it'll return false
, showing that Equals
is indeed symmetric.