C#:静态object.Equals如何检查是否相等? [英] C#: How does the static object.Equals check for equality?

查看:259
本文介绍了C#:静态object.Equals如何检查是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有两个不同的类,每个类都有自己的Equals实现;使用哪一个?如果其中只有一个人该怎么办?还是没有?以下任何行等效吗?

Say you have two different classes where each have their own implementation of 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 )

我猜前两个可能相等

它真正的作用是什么?

推荐答案

基本上,它会做三件事:

Basically it does three things:


  • 检查引用是否相等(如果是,则返回true)

  • 检查引用是否为空(如果两个值中的任何一个为空,则返回false;到现在为止已处理null == null情况)

  • 使用<$ c检查值是否相等$ c> first.Equals(second)

  • Check for reference equality (return true if so)
  • Check for reference nullity (return false if either value is null; by now the null == null case has been handled)
  • Check for value equality with first.Equals(second)

订购不应该 x.Equals(y)意味着 y.Equals(x )。但是,我安装的脱机文档确实指出了这一点。首先指定了Equals(second)(或objA.equals(objB)以使用实际参数命名)。 在线文档并没有提到这一点,很有趣。

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). 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. 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.
}

这篇关于C#:静态object.Equals如何检查是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆