[英]C#: How does the static object.Equals check for equality?
Say you have two different classes where each have their own implementation of Equals; 假设你有两个不同的类,每个类都有自己的Equals实现; which one is used? 使用哪一个? What if only one of them have one? 如果只有一个人有一个怎么办? Or none of them? 或者他们都没有? Are any of the following lines equivalent? 以下任何一行是否相同?
object .Equals( first, second )
first .Equals( second )
second .Equals( first )
I'm guessing that the first two might be equivalent, but I don't really have a clue. 我猜测前两个可能是等价的,但我真的不知道。
What does it really do? 它到底是做什么的?
Basically it does three things: 基本上它做了三件事:
first.Equals(second)
检查值是否与first.Equals(second)
相等 The ordering shouldn't matter if both values have well-behaved equality implementations, as equality should be implemented such that x.Equals(y)
implies y.Equals(x)
. 排序不应该的问题,如果这两个值都乖巧平等的实现,作为平等应该被实现,使得x.Equals(y)
意味着y.Equals(x)
However, the offline documentation I've got installed does state that first.Equals(second) (or objA.equals(objB) to use the real parameter naming) is specified. 但是,我安装的脱机文档确实指出first.Equals(second)(或objA.equals(objB)使用真实参数命名)。 The online documentation doesn't mention this, interestingly enough. 有趣的是, 在线文档没有提到这一点。
Just to make all of this concrete, the implementation could look like this: 为了使所有这些具体,实现可能如下所示:
public static bool Equals(object x, object y)
{
if (x == y) // Reference equality only; overloaded operators are ignored
{
return true;
}
if (x == null || y == null) // Again, reference checks
{
return false;
}
return x.Equals(y); // Safe as we know x != null.
}
By default, object equivalency is determined by the object's address in memory. 默认情况下,对象等效性由对象在内存中的地址决定。 If both instances have the same memory address, they are equal. 如果两个实例具有相同的内存地址,则它们是相等的。
However, this can be overloaded within the object so that developers can compare two objects that arn't in the same memory location and still be considered equal. 然而,这可以在对象内被重载以使得开发者可以比较arn't在相同的存储器位置,并且仍然被认为是相等的两个对象。 For example, if you had a Data Access Layer where each object had its data record's ID from the database, you could have object equality compared based on the ID. 例如,如果您有一个数据访问层,其中每个对象都有来自数据库的数据记录ID,则可以根据ID比较对象相等性。
You can overload operators to produce this functionality. 您可以重载运算符以生成此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.