两个.NET对象是相等的不说他们是 [英] Two .NET objects that are equal don't say they are
问题描述
我有以下代码:
object val1 = 1;
object val2 = 1;
bool result1 = (val1 == val2);//Equals false
bool result2 = val1.Equals(val2); //Equals true
什么回事?就是要解决这个问题去与.Equals()方法的唯一途径?
What's up with that? Is the only way to fix this to go with .Equals() method?
推荐答案
运营商 = =
是静态的,不是虚拟的,所以问题是由静态类型,而不是运行类型确定。该的默认的实施 ==
上引用类型的对象是比较引用(虽然类型可以实现不同的行为,例如字符串
)。你有两个不同的对象和他们没有相同的引用,以便 ==
返回false。
The operator ==
is static, not virtual, so the behaviour is determined by the static type and not the runtime type. The default implementation for ==
on objects of reference type is to compare the references (although types can implement a different behaviour, for example string
). You have two different objects and they don't have the same reference so ==
returns false.
解决方案正如你指出的,是用等于。相当于是一个虚拟的方法。由于值1
的运行时类型的Int32
你最终调用的Int32.Equals 。从.net反射,你可以看到,这个实施如下:
The solution, as you point out, is to use Equals. Equals is a virtual method. Since value1
has runtime type Int32
you end up calling Int32.Equals. From .NET Reflector you can see that the implementation of this is as follows:
public override bool Equals(object obj)
{
return ((obj is int) && (this == ((int) obj)));
}
在换句话说,它会检查参数类型是<$ C $的C> INT ,如果是将其转换并使用 ==
这是对 INT $ C $定义C>。这比较整数的值的
In other words, it checks if the argument is of type int
, and if so casts it and uses the ==
that is defined for int
. This compares the values of the integers.
时来解决这个问题去与.Equals(的唯一途径)方法?
Is the only way to fix this to go with .Equals() method?
另一种方法是投你的对象 INT
,然后使用 ==
,就像 Int32.Equals
的实施一样。
An alternative is to cast your objects to int
and then use ==
, just as the implementation of Int32.Equals
does.
这篇关于两个.NET对象是相等的不说他们是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!