共用方式為


System.Object.Equals 方法

本文提供此 API 參考文件的補充備註。

本文與 Object.Equals(Object) 方法有關。

目前實例與 obj 參數之間的比較類型取決於目前實例是參考型別還是實值型別。

  • 如果目前的實例是參考型別,則 Equals(Object) 方法會測試參考是否相等,而對方法的呼叫 Equals(Object) 相當於對 方法的 ReferenceEquals 呼叫。 參考相等表示比較的物件變數會參考相同的物件。 下列範例說明這類比較的結果。 它會定義類別 Person ,這是參考型別,並呼叫 Person 類別建構函式來具現化兩個新 Person 物件, person1a 以及 person2具有相同值的 。 它也會指定 person1a 給另一個物件變數 person1b。 如範例的輸出所示, person1aperson1b 相等,因為它們參考相同的物件。 不過, 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 的物件不等 Int32 於值為 12 的物件,因為這兩個物件的執行時類型不同。

      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 Runtime 類別可以覆寫 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 作,以測試值是否相等,而不是參考相等,並定義值相等的精確意義。 即使不是相同的實例,這類Equals的實作,如果兩個物件具有相同值,仍然會傳回true。 類型的實作器會決定構成物件值的內容,但通常是對象實例變數中儲存的部分或所有數據。 例如,物件的值是以字串的 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)方法的所有實作,下列語句都必須成立。 在清單中, xyz 代表非 Null 的物件參考。

  • 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)x 所參考的物件未被修改,連續呼叫 y 都會傳回相同的值。

  • 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# 中使用 obj is Point 的形式檢查,或在 Visual Basic 中使用 TryCast(obj, Point),即使 obj 與當前實例不屬於相同執行時型別,但當 objPoint 的衍生類別實例時,該檢查仍會回傳 true。 確認這兩個物件的類型相同,方法會轉換成 obj 類型 Point ,並傳回比較兩個對象的實例欄位的結果。

Point3D.Equals中,覆寫Point.Equals的繼承Object.Equals(Object)方法會在完成任何其他動作之前被叫用。 因為 Point3D 是密封類別 (NotInheritable在 Visual Basic 中),因此在 C# 或 obj is Point Visual Basic 中籤入表單TryCast(obj, Point)就足以確保objPoint3D 物件。 如果 Point3D 是一個物件,則會將其轉換成 Point 物件,並傳遞至 Equals 的基類實作。 只有當繼承 Point.Equals 的方法傳回 true 時,方法才會比較 z 衍生類別中引進的實例欄位。

下列範例會定義類別,該類別會在內部將矩形實作為兩RectanglePoint 物件。 類別 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 類型。