System.Object.Equals 方法

本文提供了此 API 参考文档的补充说明。

本文涉及 Object.Equals(Object) 方法。

当前实例与 obj 参数之间的比较类型取决于当前实例是引用类型还是值类型。

  • 如果当前实例是引用类型,则 Equals(Object) 方法测试引用相等性,对方法的调用 Equals(Object) 等效于对方法的 ReferenceEquals 调用。 引用相等意味着比较的对象变量引用同一对象。 下面的示例演示了此类比较的结果。 它定义一个 Person 类,该类是引用类型,并调用 Person 类构造函数来实例化两个新 Person 对象, person1a 以及 person2具有相同值的类。 它还将person1a分配给另一个对象变量person1b。 如示例中的输出所示, person1a 并且 person1b 相等,因为它们引用了同一对象。 尽管 person1aperson2 的值相同,但它们并不相等。

    using System;
    
    // Define a reference type that does not override Equals.
    public class Person
    {
       private string personName;
    
       public Person(string name)
       {
          this.personName = name;
       }
    
       public override string ToString()
       {
          return this.personName;
       }
    }
    
    public class Example1
    {
       public static void Main()
       {
          Person person1a = new Person("John");
          Person person1b = person1a;
          Person person2 = new Person(person1a.ToString());
    
          Console.WriteLine("Calling Equals:");
          Console.WriteLine($"person1a and person1b: {person1a.Equals(person1b)}");
          Console.WriteLine($"person1a and person2: {person1a.Equals(person2)}");
    
          Console.WriteLine("\nCasting to an Object and calling Equals:");
          Console.WriteLine($"person1a and person1b: {((object) person1a).Equals((object) person1b)}");
          Console.WriteLine($"person1a and person2: {((object) person1a).Equals((object) person2)}");
       }
    }
    // The example displays the following output:
    //       person1a and person1b: True
    //       person1a and person2: False
    //
    //       Casting to an Object and calling Equals:
    //       person1a and person1b: True
    //       person1a and person2: False
    
    // Define a reference type that does not override Equals.
    type Person(name) =
        override _.ToString() =
            name
    
    let person1a = Person "John"
    let person1b = person1a
    let person2 = Person(string person1a)
    
    printfn "Calling Equals:"
    printfn $"person1a and person1b: {person1a.Equals person1b}"
    printfn $"person1a and person2: {person1a.Equals person2}"
    
    printfn "\nCasting to an Object and calling Equals:"
    printfn $"person1a and person1b: {(person1a :> obj).Equals(person1b :> obj)}"
    printfn $"person1a and person2: {(person1a :> obj).Equals(person2 :> obj)}"
    // The example displays the following output:
    //       person1a and person1b: True
    //       person1a and person2: False
    //
    //       Casting to an Object and calling Equals:
    //       person1a and person1b: True
    //       person1a and person2: False
    
    ' Define a reference type that does not override Equals.
    Public Class Person1
        Private personName As String
    
        Public Sub New(name As String)
            Me.personName = name
        End Sub
    
        Public Overrides Function ToString() As String
            Return Me.personName
        End Function
    End Class
    
    Module Example0
        Public Sub Main()
            Dim person1a As New Person1("John")
            Dim person1b As Person1 = person1a
            Dim person2 As New Person1(person1a.ToString())
    
            Console.WriteLine("Calling Equals:")
            Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b))
            Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2))
            Console.WriteLine()
    
            Console.WriteLine("Casting to an Object and calling Equals:")
            Console.WriteLine("person1a and person1b: {0}", CObj(person1a).Equals(CObj(person1b)))
            Console.WriteLine("person1a and person2: {0}", CObj(person1a).Equals(CObj(person2)))
        End Sub
    End Module
    ' The example displays the following output:
    '       Calling Equals:
    '       person1a and person1b: True
    '       person1a and person2: False
    '       
    '       Casting to an Object and calling Equals:
    '       person1a and person1b: True
    '       person1a and person2: False
    
  • 如果当前实例是值类型,则 Equals(Object) 方法将测试值相等性。 值相等性表示以下内容:

    • 这两个对象的类型相同。 如以下示例所示, Byte 值为 12 的对象不等于值为 12 的对象,因为两个 Int32 对象具有不同的运行时类型。

      byte value1 = 12;
      int value2 = 12;
      
      object object1 = value1;
      object object2 = value2;
      
      Console.WriteLine($"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals(object2)}");
      
      // The example displays the following output:
      //        12 (Byte) = 12 (Int32): False
      
      let value1 = 12uy
      let value2 = 12
      
      let object1 = value1 :> obj
      let object2 = value2 :> obj
      
      printfn $"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals object2}"
      
      // The example displays the following output:
      //        12 (Byte) = 12 (Int32): False
      
      Module Example2
          Public Sub Main()
              Dim value1 As Byte = 12
              Dim value2 As Integer = 12
      
              Dim object1 As Object = value1
              Dim object2 As Object = value2
      
              Console.WriteLine("{0} ({1}) = {2} ({3}): {4}",
                              object1, object1.GetType().Name,
                              object2, object2.GetType().Name,
                              object1.Equals(object2))
          End Sub
      End Module
      ' The example displays the following output:
      '       12 (Byte) = 12 (Int32): False
      
    • 两个对象的公共字段和私有字段的值相等。 以下示例测试值相等性。 它定义一个 Person 结构,它是一个值类型,并调用 Person 类构造函数来实例化两个新 Person 对象, person1 并且 person2具有相同的值。 如示例中的输出所示,尽管这两个对象变量引用不同的对象, person1 并且 person2 相等,因为它们具有与专用 personName 字段相同的值。

      using System;
      
      // Define a value type that does not override Equals.
      public struct Person3
      {
         private string personName;
      
         public Person3(string name)
         {
            this.personName = name;
         }
      
         public override string ToString()
         {
            return this.personName;
         }
      }
      
      public struct Example3
      {
         public static void Main()
         {
            Person3 person1 = new Person3("John");
            Person3 person2 = new Person3("John");
      
            Console.WriteLine("Calling Equals:");
            Console.WriteLine(person1.Equals(person2));
      
            Console.WriteLine("\nCasting to an Object and calling Equals:");
            Console.WriteLine(((object) person1).Equals((object) person2));
         }
      }
      // The example displays the following output:
      //       Calling Equals:
      //       True
      //
      //       Casting to an Object and calling Equals:
      //       True
      
      // Define a value type that does not override Equals.
      [<Struct>]
      type Person(personName: string) =
          override _.ToString() =
              personName
      
      let person1 = Person "John"
      let person2 = Person "John"
      
      printfn "Calling Equals:"
      printfn $"{person1.Equals person2}"
      
      printfn $"\nCasting to an Object and calling Equals:"
      printfn $"{(person1 :> obj).Equals(person2 :> obj)}"
      // The example displays the following output:
      //       Calling Equals:
      //       True
      //
      //       Casting to an Object and calling Equals:
      //       True
      
      ' Define a value type that does not override Equals.
      Public Structure Person4
          Private personName As String
      
          Public Sub New(name As String)
              Me.personName = name
          End Sub
      
          Public Overrides Function ToString() As String
              Return Me.personName
          End Function
      End Structure
      
      Module Example4
          Public Sub Main()
              Dim p1 As New Person4("John")
              Dim p2 As New Person4("John")
      
              Console.WriteLine("Calling Equals:")
              Console.WriteLine(p1.Equals(p2))
              Console.WriteLine()
      
              Console.WriteLine("Casting to an Object and calling Equals:")
              Console.WriteLine(CObj(p1).Equals(p2))
          End Sub
      End Module
      ' The example displays the following output:
      '       Calling Equals:
      '       True
      '       
      '       Casting to an Object and calling Equals:
      '       True
      

由于该 Object 类是 .NET 中所有类型的基类,因此该方法 Object.Equals(Object) 为所有其他类型提供默认相等比较。 但是,类型通常会替代 Equals 方法来实现值相等性。 有关详细信息,请参阅“对调用者的说明”和“对继承者的说明”部分。

Windows 运行时的说明

在 Windows 运行时中对类调用 Equals(Object) 方法重载时,它为不重写 Equals(Object)的类提供默认行为。 这是 .NET 为 Windows 运行时提供的支持的一部分(请参阅 Windows 应用商店应用和 Windows 运行时的 .NET 支持)。 Windows 运行时中的类不会继承 Object,当前不实现方法 Equals(Object) 。 但是,在 C# 或 Visual Basic 代码中使用它们时,它们似乎具有ToStringEquals(Object)GetHashCode方法,.NET 为这些方法提供了默认行为。

注释

用 C# 或 Visual Basic 编写的 Windows 运行时类可以替代 Equals(Object) 方法重载。

呼叫者注意事项

派生类经常替代 Object.Equals(Object) 方法来实现值相等性。 此外,类型通常会通过实现Equals接口,为IEquatable<T>方法提供额外的强类型重载。 在调用 Equals 方法进行相等性测试时,您应知道当前实例是否重写了 Object.Equals,以及理解如何解析 Equals 方法的特定调用。 否则,可能会对与预期值不同的相等性执行测试,并且该方法可能会返回意外值。

下面的示例进行了这方面的演示。 它实例化三 StringBuilder 个具有相同字符串的对象,然后对方法进行四次调用 Equals 。 第一个方法调用返回 true,其余三个返回 false

using System;
using System.Text;

public class Example5
{
   public static void Main()
   {
      StringBuilder sb1 = new StringBuilder("building a string...");
      StringBuilder sb2 = new StringBuilder("building a string...");

      Console.WriteLine($"sb1.Equals(sb2): {sb1.Equals(sb2)}");
      Console.WriteLine($"((Object) sb1).Equals(sb2): {((Object) sb1).Equals(sb2)}");
      Console.WriteLine($"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}");

      Object sb3 = new StringBuilder("building a string...");
      Console.WriteLine($"\nsb3.Equals(sb2): {sb3.Equals(sb2)}");
   }
}
// The example displays the following output:
//       sb1.Equals(sb2): True
//       ((Object) sb1).Equals(sb2): False
//       Object.Equals(sb1, sb2): False
//
//       sb3.Equals(sb2): False
open System
open System.Text

let sb1 = StringBuilder "building a string..."
let sb2 = StringBuilder "building a string..."

printfn $"sb1.Equals(sb2): {sb1.Equals sb2}"
printfn $"((Object) sb1).Equals(sb2): {(sb1 :> obj).Equals sb2}"
                  
printfn $"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}"

let sb3 = StringBuilder "building a string..."
printfn $"\nsb3.Equals(sb2): {sb3.Equals sb2}"
// The example displays the following output:
//       sb1.Equals(sb2): True
//       ((Object) sb1).Equals(sb2): False
//       Object.Equals(sb1, sb2): False
//
//       sb3.Equals(sb2): False
Imports System.Text

Module Example5
    Public Sub Main()
        Dim sb1 As New StringBuilder("building a string...")
        Dim sb2 As New StringBuilder("building a string...")

        Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2))
        Console.WriteLine("CObj(sb1).Equals(sb2): {0}",
                        CObj(sb1).Equals(sb2))
        Console.WriteLine("Object.Equals(sb1, sb2): {0}",
                        Object.Equals(sb1, sb2))

        Console.WriteLine()
        Dim sb3 As Object = New StringBuilder("building a string...")
        Console.WriteLine("sb3.Equals(sb2): {0}", sb3.Equals(sb2))
    End Sub
End Module
' The example displays the following output:
'       sb1.Equals(sb2): True
'       CObj(sb1).Equals(sb2): False
'       Object.Equals(sb1, sb2): False
'
'       sb3.Equals(sb2): False

在第一种情况下,会调用强类型的 StringBuilder.Equals(StringBuilder) 方法重载来测试值的相等性。 由于分配给这两 StringBuilder 个对象的字符串相等,因此该方法返回 true。 但是,StringBuilder 不覆盖 Object.Equals(Object)。 因此,当StringBuilder对象被强制转换为Object对象时,当StringBuilder实例被赋给类型为Object的变量时,以及当Object.Equals(Object, Object)方法被传递两个StringBuilder对象时,将调用默认Object.Equals(Object)方法。 由于 StringBuilder 是引用类型,这等效于将两 StringBuilder 个对象传递给 ReferenceEquals 该方法。 尽管所有三 StringBuilder 个对象都包含相同的字符串,但它们引用三个不同的对象。 因此,这三个方法调用将返回 false

可以通过调用 ReferenceEquals 该方法,将当前对象与另一个对象进行比较,以保持引用相等性。 在 Visual Basic 中,还可以使用 is 关键字(例如, If Me Is otherObject Then ...)。

给继承者的须知

定义自己的类型时,该类型将继承其基类型方法定义的 Equals 功能。 下表列出了 .NET 中主要类型类别的 Equals 方法的默认实现。

类型类别 定义相等性的值 注释
直接从Object派生的类 Object.Equals(Object) 引用相等性;等效于调用 Object.ReferenceEquals
结构 ValueType.Equals 价值相等; 直接进行字节对字节的比较或使用反射进行逐字段的比较。
枚举 Enum.Equals 值必须具有相同的枚举类型和相同的基础值。
委托 MulticastDelegate.Equals 委托必须具有相同的类型和相同的调用列表。
接口 Object.Equals(Object) 引用相等性。

对于值类型,应始终替代 Equals,因为依赖反射的相等性测试性能较差。 还可以重写引用类型的默认实现Equals,以测试值相等性而不是引用相等性,并定义值相等性的精确定义。 此类实现如果两个对象具有相同的值,即使它们不是同一实例,也会返回Equalstrue。 该类型的实现程序决定构成对象值的内容,但通常是对象实例变量中存储的部分或所有数据。 例如,String 对象的值基于字符串的字符;String.Equals(Object) 方法重写了 Object.Equals(Object) 方法,以返回 true,用于任意两个包含相同字符且顺序相同的字符串实例。

以下示例展示了如何替代 Object.Equals(Object) 方法来测试数值相等性。 它会替代 Equals 类的 Person 方法。 如果 Person 接受其基类实现相等,则仅当两 Person 个对象引用单个对象时才相等。 但是,在这种情况下,如果两个对象具有Person相同的属性值,则两Person.Id个对象相等。

public class Person6
{
   private string idNumber;
   private string personName;

   public Person6(string name, string id)
   {
      this.personName = name;
      this.idNumber = id;
   }

   public override bool Equals(Object obj)
   {
      Person6 personObj = obj as Person6;
      if (personObj == null)
         return false;
      else
         return idNumber.Equals(personObj.idNumber);
   }

   public override int GetHashCode()
   {
      return this.idNumber.GetHashCode();
   }
}

public class Example6
{
   public static void Main()
   {
      Person6 p1 = new Person6("John", "63412895");
      Person6 p2 = new Person6("Jack", "63412895");
      Console.WriteLine(p1.Equals(p2));
      Console.WriteLine(Object.Equals(p1, p2));
   }
}
// The example displays the following output:
//       True
//       True
open System

type Person(name, id) =
    member _.Name = name
    member _.Id = id

    override _.Equals(obj) =
        match obj with
        | :? Person as personObj ->
            id.Equals personObj.Id
        | _ -> 
            false

    override _.GetHashCode() =
        id.GetHashCode()

let p1 = Person("John", "63412895")
let p2 = Person("Jack", "63412895")
printfn $"{p1.Equals p2}"
printfn $"{Object.Equals(p1, p2)}"
// The example displays the following output:
//       True
//       True
Public Class Person
   Private idNumber As String
   Private personName As String
   
   Public Sub New(name As String, id As String)
      Me.personName = name
      Me.idNumber = id
   End Sub
   
   Public Overrides Function Equals(obj As Object) As Boolean
      Dim personObj As Person = TryCast(obj, Person) 
      If personObj Is Nothing Then
         Return False
      Else
         Return idNumber.Equals(personObj.idNumber)
      End If   
   End Function
   
   Public Overrides Function GetHashCode() As Integer
      Return Me.idNumber.GetHashCode() 
   End Function
End Class

Module Example6
    Public Sub Main()
        Dim p1 As New Person("John", "63412895")
        Dim p2 As New Person("Jack", "63412895")
        Console.WriteLine(p1.Equals(p2))
        Console.WriteLine(Object.Equals(p1, p2))
    End Sub
End Module
' The example displays the following output:
'       True
'       True

除了替代 Equals 之外,还可以实现 IEquatable<T> 接口,以提供强类型的相等性测试。

对于 Equals(Object) 方法的所有实现,以下语句必须为 true。 在列表中,xy表示znull 的对象引用。

  • x.Equals(x) 返回 true

  • x.Equals(y) 返回与 . 相同的值 y.Equals(x)

  • x.Equals(y)truex都为y时返回NaN

  • 如果 (x.Equals(y) && y.Equals(z)) 返回 true,则 x.Equals(z) 返回 true

  • 连续调用 x.Equals(y) 将返回相同的值,只要 xy 指向的对象没有被修改。

  • x.Equals(null) 返回 false

实现 Equals 不能引发异常;它们应始终返回值。 例如,如果objnull,则Equals方法应返回false而不是引发ArgumentNullException

重写 Equals(Object)时遵循以下准则:

  • 实现IComparable的类型必须覆盖Equals(Object)

  • 重写 Equals(Object) 的类型也必须重写 GetHashCode;否则,哈希表可能无法正常工作。

  • 应该考虑实现 IEquatable<T> 接口以支持强类型相等性测试。 IEquatable<T>.Equals 实现应返回与 Equals 一致的结果。

  • 如果您的编程语言支持运算符重载,并且您为某一类型重载了相等运算符,则还必须重写Equals(Object)方法,以使其返回与相等运算符相同的结果。 这有助于确保使用 Equals (如 ArrayListHashtable)的类库代码的行为方式与应用程序代码使用相等运算符的方式一致。

参考类型指南

以下指南适用于替代引用类型的 Equals(Object)

  • 如果类型的语义是基于该类型表示某些值这一事实,可以考虑替代 Equals

  • 大多数引用类型不得重载相等性运算符,即使它们替代了 Equals。 但是,如果要实现一个具有值语义的引用类型(如复数类型),则必须替代相等性运算符。

  • 不应在可变引用类型上替代 Equals。 这是因为替代 Equals 需要同时也替代 GetHashCode 方法,如上一节所述。 这意味着可变引用类型的实例的哈希代码在其生存期内可能会更改,这可能导致对象在哈希表中丢失。

值类型准则

以下指南适用于替代值类型的 Equals(Object)

  • 如果定义的值类型包含一个或多个值为引用类型的字段,则应替代 Equals(Object)Equals(Object)ValueType中实现的代码对其中字段全部为值类型的值类型执行逐字节比较,但对于字段中包含引用类型的值类型,则使用反射进行逐字段比较。

  • 如果替代 Equals 并且开发语言支持运算符重载,则必须重载相等性运算符。

  • 应实现 IEquatable<T> 接口。 调用强类型 IEquatable<T>.Equals 方法可避免将 obj 参数装箱。

例子

下面的示例演示一个 Point 类,该类重写了 Equals 方法以实现值相等性,还有一个 Point3D 类,该类是从 Point 派生的。 由于 Point 重写 Object.Equals(Object) 用于测试值相等性, Object.Equals(Object) 因此不调用该方法。 但是, Point3D.Equals 调用 Point.Equals 是因为 Point 以提供值相等的方式实现 Object.Equals(Object)

using System;

class Point2
{
    protected int x, y;

    public Point2() : this(0, 0)
    { }

    public Point2(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override bool Equals(Object obj)
    {
        //Check for null and compare run-time types.
        if ((obj == null) || !this.GetType().Equals(obj.GetType()))
        {
            return false;
        }
        else
        {
            Point2 p = (Point2)obj;
            return (x == p.x) && (y == p.y);
        }
    }

    public override int GetHashCode()
    {
        return (x << 2) ^ y;
    }

    public override string ToString()
    {
        return String.Format("Point2({0}, {1})", x, y);
    }
}

sealed class Point3D : Point2
{
    int z;

    public Point3D(int x, int y, int z) : base(x, y)
    {
        this.z = z;
    }

    public override bool Equals(Object obj)
    {
        Point3D pt3 = obj as Point3D;
        if (pt3 == null)
            return false;
        else
            return base.Equals((Point2)obj) && z == pt3.z;
    }

    public override int GetHashCode()
    {
        return (base.GetHashCode() << 2) ^ z;
    }

    public override String ToString()
    {
        return String.Format("Point2({0}, {1}, {2})", x, y, z);
    }
}

class Example7
{
    public static void Main()
    {
        Point2 point2D = new Point2(5, 5);
        Point3D point3Da = new Point3D(5, 5, 2);
        Point3D point3Db = new Point3D(5, 5, 2);
        Point3D point3Dc = new Point3D(5, 5, -1);

        Console.WriteLine($"{point2D} = {point3Da}: {point2D.Equals(point3Da)}");
        Console.WriteLine($"{point2D} = {point3Db}: {point2D.Equals(point3Db)}");
        Console.WriteLine($"{point3Da} = {point3Db}: {point3Da.Equals(point3Db)}");
        Console.WriteLine($"{point3Da} = {point3Dc}: {point3Da.Equals(point3Dc)}");
    }
}
// The example displays the following output:
//       Point2(5, 5) = Point2(5, 5, 2): False
//       Point2(5, 5) = Point2(5, 5, 2): False
//       Point2(5, 5, 2) = Point2(5, 5, 2): True
//       Point2(5, 5, 2) = Point2(5, 5, -1): False
type Point(x, y) =
    new () = Point(0, 0)
    member _.X = x
    member _.Y = y

    override _.Equals(obj) =
        //Check for null and compare run-time types.
        match obj with
        | :? Point as p ->
            x = p.X && y = p.Y
        | _ -> 
            false

    override _.GetHashCode() =
        (x <<< 2) ^^^ y

    override _.ToString() =
        $"Point({x}, {y})"

type Point3D(x, y, z) =
    inherit Point(x, y)
    member _.Z = z

    override _.Equals(obj) =
        match obj with
        | :? Point3D as pt3 ->
            base.Equals(pt3 :> Point) && z = pt3.Z
        | _ -> 
            false

    override _.GetHashCode() =
        (base.GetHashCode() <<< 2) ^^^ z

    override _.ToString() =
        $"Point({x}, {y}, {z})"

let point2D = Point(5, 5)
let point3Da = Point3D(5, 5, 2)
let point3Db = Point3D(5, 5, 2)
let point3Dc = Point3D(5, 5, -1)

printfn $"{point2D} = {point3Da}: {point2D.Equals point3Da}"
printfn $"{point2D} = {point3Db}: {point2D.Equals point3Db}"
printfn $"{point3Da} = {point3Db}: {point3Da.Equals point3Db}"
printfn $"{point3Da} = {point3Dc}: {point3Da.Equals point3Dc}"
// The example displays the following output:
//       Point(5, 5) = Point(5, 5, 2): False
//       Point(5, 5) = Point(5, 5, 2): False
//       Point(5, 5, 2) = Point(5, 5, 2): True
//       Point(5, 5, 2) = Point(5, 5, -1): False
Class Point1
    Protected x, y As Integer

    Public Sub New()
        Me.x = 0
        Me.y = 0
    End Sub

    Public Sub New(x As Integer, y As Integer)
        Me.x = x
        Me.y = y
    End Sub

    Public Overrides Function Equals(obj As Object) As Boolean
        ' Check for null and compare run-time types.
        If obj Is Nothing OrElse Not Me.GetType().Equals(obj.GetType()) Then
            Return False
        Else
            Dim p As Point1 = DirectCast(obj, Point1)
            Return x = p.x AndAlso y = p.y
        End If
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return (x << 2) Xor y
    End Function

    Public Overrides Function ToString() As String
        Return String.Format("Point1({0}, {1})", x, y)
    End Function
End Class

Class Point3D : Inherits Point1
    Private z As Integer

    Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer)
        MyBase.New(x, y)
        Me.z = z
    End Sub

    Public Overrides Function Equals(ByVal obj As Object) As Boolean
        Dim pt3 As Point3D = TryCast(obj, Point3D)
        If pt3 Is Nothing Then
            Return False
        Else
            Return MyBase.Equals(CType(pt3, Point1)) AndAlso z = pt3.z
        End If
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return (MyBase.GetHashCode() << 2) Xor z
    End Function

    Public Overrides Function ToString() As String
        Return String.Format("Point1({0}, {1}, {2})", x, y, z)
    End Function
End Class

Module Example1
    Public Sub Main()
        Dim point2D As New Point1(5, 5)
        Dim point3Da As New Point3D(5, 5, 2)
        Dim point3Db As New Point3D(5, 5, 2)
        Dim point3Dc As New Point3D(5, 5, -1)

        Console.WriteLine("{0} = {1}: {2}",
                          point2D, point3Da, point2D.Equals(point3Da))
        Console.WriteLine("{0} = {1}: {2}",
                          point2D, point3Db, point2D.Equals(point3Db))
        Console.WriteLine("{0} = {1}: {2}",
                          point3Da, point3Db, point3Da.Equals(point3Db))
        Console.WriteLine("{0} = {1}: {2}",
                          point3Da, point3Dc, point3Da.Equals(point3Dc))
    End Sub
End Module
' The example displays the following output
'       Point1(5, 5) = Point1(5, 5, 2): False
'       Point1(5, 5) = Point1(5, 5, 2): False
'       Point1(5, 5, 2) = Point1(5, 5, 2): True
'       Point1(5, 5, 2) = Point1(5, 5, -1): False

该方法 Point.Equals 检查以确保 obj 参数不 为 null ,并且它引用的实例与此对象的类型相同。 如果任一检查失败,该方法将 false返回 。

该方法 Point.Equals 调用 GetType 该方法来确定这两个对象的运行时类型是否相同。 如果该方法在 C# 或者 Visual Basic 中使用形式为 obj is Point 的检查,那么当 TryCast(obj, Point) 是派生类 true 的实例时,检查将返回 obj,即使 Point 和当前实例并不是相同的运行时类型。 确认这两个对象的类型相同后,该方法将 obj 强制转换为 Point 类型,并返回比较这两个对象的实例字段的结果。

Point3D.Equals 中,首先调用替代 Point.Equals 的继承 Object.Equals(Object) 方法,然后再执行其他操作。 由于Point3D是一个密封类(NotInheritable在 Visual Basic 中),因此在 C# 中使用obj is Point或在 Visual Basic 中使用TryCast(obj, Point)进行检查足以确保obj是一个Point3D对象。 如果它是对象 Point3D ,则将其强制转换为 Point 对象并传递给基类实现 Equals。 仅当继承 Point.Equals 的方法返回 true 时,该方法才会比较 z 派生类中引入的实例字段。

以下示例定义一个Rectangle类,该类在内部将一个矩形实现为两个Point对象。 Rectangle 类还会替代 Object.Equals(Object) 以实现值相等性。

using System;

class Rectangle
{
   private Point a, b;

   public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY)
   {
      this.a = new Point(upLeftX, upLeftY);
      this.b = new Point(downRightX, downRightY);
   }

   public override bool Equals(Object obj)
   {
      // Perform an equality check on two rectangles (Point object pairs).
      if (obj == null || GetType() != obj.GetType())
          return false;
      Rectangle r = (Rectangle)obj;
      return a.Equals(r.a) && b.Equals(r.b);
   }

   public override int GetHashCode()
   {
      return Tuple.Create(a, b).GetHashCode();
   }

    public override String ToString()
    {
       return String.Format("Rectangle({0}, {1}, {2}, {3})",
                            a.x, a.y, b.x, b.y);
    }
}

class Point
{
  internal int x;
  internal int y;

  public Point(int X, int Y)
  {
     this.x = X;
     this.y = Y;
  }

  public override bool Equals (Object obj)
  {
     // Performs an equality check on two points (integer pairs).
     if (obj == null || GetType() != obj.GetType()) return false;
     Point p = (Point)obj;
     return (x == p.x) && (y == p.y);
  }

  public override int GetHashCode()
  {
     return Tuple.Create(x, y).GetHashCode();
  }
}

class Example
{
   public static void Main()
   {
      Rectangle r1 = new Rectangle(0, 0, 100, 200);
      Rectangle r2 = new Rectangle(0, 0, 100, 200);
      Rectangle r3 = new Rectangle(0, 0, 150, 200);

      Console.WriteLine($"{r1} = {r2}: {r1.Equals(r2)}");
      Console.WriteLine($"{r1} = {r3}: {r1.Equals(r3)}");
      Console.WriteLine($"{r2} = {r3}: {r2.Equals(r3)}");
   }
}
// The example displays the following output:
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
type Point(x, y) =
    member _.X = x
    member _.Y = y

    override _.Equals(obj) =
        // Performs an equality check on two points (integer pairs).
        match obj with
        | :? Point as p ->
            x = p.X && y = p.Y
        | _ ->
            false
    
    override _.GetHashCode() =
        (x, y).GetHashCode()

type Rectangle(upLeftX, upLeftY, downRightX, downRightY) =
    let a = Point(upLeftX, upLeftY)
    let b = Point(downRightX, downRightY)
    
    member _.UpLeft = a
    member _.DownRight = b

    override _.Equals(obj) =
        // Perform an equality check on two rectangles (Point object pairs).
        match obj with
        | :? Rectangle as r ->
            a.Equals(r.UpLeft) && b.Equals(r.DownRight)
        | _ -> 
            false
        
    override _.GetHashCode() =
        (a, b).GetHashCode()

    override _.ToString() =
       $"Rectangle({a.X}, {a.Y}, {b.X}, {b.Y})"

let r1 = Rectangle(0, 0, 100, 200)
let r2 = Rectangle(0, 0, 100, 200)
let r3 = Rectangle(0, 0, 150, 200)

printfn $"{r1} = {r2}: {r1.Equals r2}"
printfn $"{r1} = {r3}: {r1.Equals r3}"
printfn $"{r2} = {r3}: {r2.Equals r3}"
// The example displays the following output:
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
Class Rectangle 
    Private a, b As Point
    
    Public Sub New(ByVal upLeftX As Integer, ByVal upLeftY As Integer, _
                   ByVal downRightX As Integer, ByVal downRightY As Integer) 
        Me.a = New Point(upLeftX, upLeftY)
        Me.b = New Point(downRightX, downRightY)
    End Sub 
    
    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        ' Performs an equality check on two rectangles (Point object pairs).
        If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
            Return False
        End If
        Dim r As Rectangle = CType(obj, Rectangle)
        Return a.Equals(r.a) AndAlso b.Equals(r.b)
    End Function

    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(a, b).GetHashCode()
    End Function 

    Public Overrides Function ToString() As String
       Return String.Format("Rectangle({0}, {1}, {2}, {3})",
                            a.x, a.y, b.x, b.y) 
    End Function
End Class 

Class Point
    Friend x As Integer
    Friend y As Integer
    
    Public Sub New(ByVal X As Integer, ByVal Y As Integer) 
        Me.x = X
        Me.y = Y
    End Sub 

    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        ' Performs an equality check on two points (integer pairs).
        If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
            Return False
        Else
           Dim p As Point = CType(obj, Point)
           Return x = p.x AndAlso y = p.y
        End If
    End Function 
    
    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(x, y).GetHashCode()
    End Function 
End Class  

Class Example
    Public Shared Sub Main() 
        Dim r1 As New Rectangle(0, 0, 100, 200)
        Dim r2 As New Rectangle(0, 0, 100, 200)
        Dim r3 As New Rectangle(0, 0, 150, 200)
        
        Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2))
        Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3))
        Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3))
    End Sub 
End Class 
' The example displays the following output:
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False

某些语言(如 C# 和 Visual Basic)支持运算符重载。 当一个类型重载相等性运算符时,它还必须替代 Equals(Object) 方法,以提供相同的功能。 这通常是通过使用重载的相等性运算符来编写 Equals(Object) 方法实现的,如下例所示。

using System;

public struct Complex
{
   public double re, im;

   public override bool Equals(Object obj)
   {
      return obj is Complex && this == (Complex)obj;
   }

   public override int GetHashCode()
   {
      return Tuple.Create(re, im).GetHashCode();
   }

   public static bool operator ==(Complex x, Complex y)
   {
      return x.re == y.re && x.im == y.im;
   }

   public static bool operator !=(Complex x, Complex y)
   {
      return !(x == y);
   }

    public override String ToString()
    {
       return String.Format("({0}, {1})", re, im);
    }
}

class MyClass
{
  public static void Main()
  {
    Complex cmplx1, cmplx2;

    cmplx1.re = 4.0;
    cmplx1.im = 1.0;

    cmplx2.re = 2.0;
    cmplx2.im = 1.0;

    Console.WriteLine($"{cmplx1} <> {cmplx2}: {cmplx1 != cmplx2}");
    Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");

    cmplx2.re = 4.0;

    Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1 == cmplx2}");
    Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");
  }
}
// The example displays the following output:
//       (4, 1) <> (2, 1): True
//       (4, 1) = (2, 1): False
//       (4, 1) = (4, 1): True
//       (4, 1) = (4, 1): True
[<Struct; CustomEquality; NoComparison>]
type Complex =
    val mutable re: double
    val mutable im: double

    override this.Equals(obj) =
        match obj with 
        | :? Complex as c when c = this -> true
        | _ -> false 

    override this.GetHashCode() =
        (this.re, this.im).GetHashCode()

    override this.ToString() =
        $"({this.re}, {this.im})"

    static member op_Equality (x: Complex, y: Complex) =
        x.re = y.re && x.im = y.im

    static member op_Inequality (x: Complex, y: Complex) =
        x = y |> not

let mutable cmplx1 = Complex()
let mutable cmplx2 = Complex()

cmplx1.re <- 4.0
cmplx1.im <- 1.0

cmplx2.re <- 2.0
cmplx2.im <- 1.0

printfn $"{cmplx1} <> {cmplx2}: {cmplx1 <> cmplx2}"
printfn $"{cmplx1} = {cmplx2}: {cmplx1.Equals cmplx2}"

cmplx2.re <- 4.0

printfn $"{cmplx1} = {cmplx2}: {cmplx1 = cmplx2}"
printfn $"{cmplx1} = {cmplx2}: {cmplx1.Equals cmplx2}"

// The example displays the following output:
//       (4, 1) <> (2, 1): True
//       (4, 1) = (2, 1): False
//       (4, 1) = (4, 1): True
//       (4, 1) = (4, 1): True
Public Structure Complex
    Public re, im As Double
    
    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        Return TypeOf obj Is Complex AndAlso Me = CType(obj, Complex)
    End Function 
    
    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(re, im).GetHashCode()
    End Function 
    
    Public Shared Operator = (x As Complex, y As Complex) As Boolean
       Return x.re = y.re AndAlso x.im = y.im
    End Operator 
    
    Public Shared Operator <> (x As Complex, y As Complex) As Boolean
       Return Not (x = y)
    End Operator 
    
    Public Overrides Function ToString() As String
       Return String.Format("({0}, {1})", re, im)
    End Function 
End Structure

Class Example8
    Public Shared Sub Main()
        Dim cmplx1, cmplx2 As Complex

        cmplx1.re = 4.0
        cmplx1.im = 1.0

        cmplx2.re = 2.0
        cmplx2.im = 1.0

        Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 <> cmplx2)
        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))

        cmplx2.re = 4.0

        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 = cmplx2)
        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))
    End Sub
End Class
' The example displays the following output:
'       (4, 1) <> (2, 1): True
'       (4, 1) = (2, 1): False
'       (4, 1) = (4, 1): True
'       (4, 1) = (4, 1): True

由于 Complex 是值类型,因此无法从中派生它。 因此,重写 Equals(Object) 方法不需要调用 GetType 来确定每个对象的精确运行时类型,但可以改用 is C# 中的运算符或 TypeOf Visual Basic 中的运算符来检查参数的类型 obj