Object.Equals 方法

定義

判斷兩種物件執行個體是否相同。Determines whether two object instances are equal.

多載

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

Equals(Object, Object)

判斷指定的物件執行個體是否視為相等。Determines whether the specified object instances are considered equal.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

public:
 virtual bool Equals(System::Object ^ obj);
public virtual bool Equals (object obj);
public virtual bool Equals (object? obj);
abstract member Equals : obj -> bool
override this.Equals : obj -> bool
Public Overridable Function Equals (obj As Object) As Boolean

參數

obj
Object

要與目前物件比較的物件。The object to compare with the current object.

傳回

Boolean

若指定的物件等於目前的物件,則為 true;否則為 falsetrue if the specified object is equal to the current object; otherwise, false.

範例

下列範例顯示的 Point 類別會覆寫 Equals 方法以提供值相等,以及 Point3D 衍生自的類別 PointThe following example shows a Point class that overrides the Equals method to provide value equality, and a Point3D class that is derived from Point. 因為 Point 覆寫 Object.Equals(Object) 會測試值是否相等,所以 Object.Equals(Object) 不會呼叫方法。Because Point overrides Object.Equals(Object) to test for value equality, the Object.Equals(Object) method is not called. 不過, Point3D.Equals 會呼叫, Point.Equals 因為 Point Object.Equals(Object) 會以提供值相等的方式來實行。However, Point3D.Equals calls Point.Equals because Point implements Object.Equals(Object) in a manner that provides value equality.

using System;

class Point
{
   protected int x, y;

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

   public Point(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 {
         Point p = (Point) obj;
         return (x == p.x) && (y == p.y);
      }
   }

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

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

sealed class Point3D: Point
{
   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((Point)obj) && z == pt3.z;
   }

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

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

class Example
{
  public static void Main()
  {
     Point point2D = new Point(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("{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));
  }
}
// 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 Point
    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 Point = DirectCast(obj, Point)
           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("Point({0}, {1})", x, y)
    End Function
End Class

Class Point3D : Inherits Point
    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, Point)) 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("Point({0}, {1}, {2})", x, y, z)
    End Function
End Class 

Module Example
    Public Sub Main() 
        Dim point2D As New Point(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
'       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

Point.Equals方法會檢查以確定 obj 引數不是 null ,而且它參考的實例類型與此物件相同。The Point.Equals method checks to make sure that the obj argument is not null and that it references an instance of the same type as this object. 如果其中一項檢查失敗,則方法會傳回 falseIf either check fails, the method returns false.

Point.Equals方法 GetType 會呼叫方法,以判斷兩個物件的執行時間類型是否相同。The Point.Equals method calls the GetType method to determine whether the run-time types of the two objects are identical. 如果方法使用 obj is Point c # 或 Visual Basic 中的表單檢查 TryCast(obj, Point) ,則 trueobj 是衍生類別的實例時,就會傳回檢查 Point ,即使 obj 目前的實例不是相同的執行時間型別也是一樣。If the method used a check of the form obj is Point in C# or TryCast(obj, Point) in Visual Basic, the check would return true in cases where obj is an instance of a derived class of Point, even though obj and the current instance are not of the same run-time type. 確認這兩個物件都屬於相同類型時,方法會轉換 obj 成類型, Point 並傳回比較兩個物件的實例欄位的結果。Having verified that both objects are of the same type, the method casts obj to type Point and returns the result of comparing the instance fields of the two objects.

在中 Point3D.Equals ,繼承的 Point.Equals 方法(覆寫 Object.Equals(Object) )會在完成其他任何作業之前叫用。In Point3D.Equals, the inherited Point.Equals method, which overrides Object.Equals(Object), is invoked before anything else is done. 因為 Point3D 是 Visual Basic) 中 (的密封類別 NotInheritable ,所以 obj is Point 在 c # 或 Visual Basic 中的表單檢查 TryCast(obj, Point) 是否足以確保 objPoint3D 物件。Because Point3D is a sealed class (NotInheritable in Visual Basic), a check in the form obj is Point in C# or TryCast(obj, Point) in Visual Basic is adequate to ensure that obj is a Point3D object. 如果它是 Point3D 物件,則會轉換成物件, Point 並傳遞至的基類實作為 EqualsIf it is a Point3D object, it is cast to a Point object and passed to the base class implementation of Equals. 只有當繼承的 Point.Equals 方法傳回時 true ,方法會比較 z 衍生類別中引進的實例欄位。Only when the inherited Point.Equals method returns true does the method compare the z instance fields introduced in the derived class.

下列範例會定義一個 Rectangle 類別,該類別會在內部將矩形實作為兩個 Point 物件。The following example defines a Rectangle class that internally implements a rectangle as two Point objects. Rectangle類別也會覆寫 Object.Equals(Object) 以提供值相等。The Rectangle class also overrides Object.Equals(Object) to provide for value equality.

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("{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));
   }
}
// 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)支援運算子多載。Some languages such as C# and Visual Basic support operator overloading. 當型別多載等號比較運算子時,它也必須覆寫 Equals(Object) 方法以提供相同的功能。When a type overloads the equality operator, it must also override the Equals(Object) method to provide the same functionality. 這通常是藉由以多載的 Equals(Object) 相等運算子撰寫方法來完成,如下列範例所示。This is typically accomplished by writing the Equals(Object) method in terms of the overloaded equality operator, as in the following example.

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("{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));
  }
}
// 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 Example
   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 是實值型別,所以不能衍生自。Because Complex is a value type, it cannot be derived from. 因此,對方法的覆寫 Equals(Object) 不需要呼叫 GetType 來判斷每個物件的精確執行時間類型,但是可以改為使用 is c # 中的運算子或 TypeOf Visual Basic 中的運算子來檢查參數的型別 objTherefore, the override to Equals(Object) method need not call GetType to determine the precise run-time type of each object, but can instead use the is operator in C# or the TypeOf operator in Visual Basic to check the type of the obj parameter.

備註

目前的實例和參數之間的比較類型, obj 取決於目前的實例是參考型別或實值型別。The type of comparison between the current instance and the obj parameter depends on whether the current instance is a reference type or a value type.

  • 如果目前的實例是參考型別,則 Equals(Object) 方法會測試參考是否相等,而且對方法的呼叫 Equals(Object) 相當於方法的呼叫 ReferenceEqualsIf the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. 參考相等表示所比較的物件變數會參考相同的物件。Reference equality means that the object variables that are compared refer to the same object. 下列範例說明這類比較的結果。The following example illustrates the result of such a comparison. 它會定義 Person 類別(即參考型別),並呼叫類別的函式來具現 Person 化兩個新 Person 的物件, person1a 以及 person2 具有相同值的。It defines a Person class, which is a reference type, and calls the Person class constructor to instantiate two new Person objects, person1a and person2, which have the same value. 它也會指派 person1a 給另一個物件變數 person1bIt also assigns person1a to another object variable, person1b. 如範例的輸出所示, person1a 而且 person1b 是相等的,因為它們參考相同的物件。As the output from the example shows, person1a and person1b are equal because they reference the same object. 不過, person1aperson2 不相等,雖然它們具有相同的值。However, person1a and person2 are not equal, although they have the same value.

    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 Example
    {
       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: {0}", person1a.Equals(person1b));
          Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2));
    
          Console.WriteLine("\nCasting to an Object and calling Equals:");
          Console.WriteLine("person1a and person1b: {0}", ((object) person1a).Equals((object) person1b));
          Console.WriteLine("person1a and person2: {0}", ((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.
    Public Class Person
       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 Example
       Public Sub Main()
          Dim person1a As New Person("John")
          Dim person1b As Person = person1a
          Dim person2 As New Person(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) 方法會測試值是否相等。If the current instance is a value type, the Equals(Object) method tests for value equality. 值相等表示下列各項:Value equality means the following:

    • 這兩個物件的類型相同。The two objects are of the same type. 如下列範例所示, Byte 具有值12的物件不等於 Int32 具有值12的物件,因為這兩個物件有不同的執行時間類型。As the following example shows, a Byte object that has a value of 12 does not equal an Int32 object that has a value of 12, because the two objects have different run-time types.

      byte value1 = 12;
      int value2 = 12;
      
      object object1 = value1;
      object object2 = value2;
      
      Console.WriteLine("{0} ({1}) = {2} ({3}): {4}",
                        object1, object1.GetType().Name,
                        object2, object2.GetType().Name,
                        object1.Equals(object2));
      
      // The example displays the following output:
      //        12 (Byte) = 12 (Int32): False
      
      Module Example
         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
      
    • 這兩個物件的公用和私用欄位值相等。The values of the public and private fields of the two objects are equal. 下列範例會測試值是否相等。The following example tests for value equality. 它會定義 Person 結構,也就是實值型別,而且會呼叫類別的函式來具現 Person 化兩個新 Person 的物件, person1 以及 person2 具有相同值的。It defines a Person structure, which is a value type, and calls the Person class constructor to instantiate two new Person objects, person1 and person2, which have the same value. 如同範例的輸出所示,雖然這兩個物件變數參考不同的物件, person1 而且 person2 是相等的,因為它們的私用欄位具有相同的值 personNameAs the output from the example shows, although the two object variables refer to different objects, person1 and person2 are equal because they have the same value for the private personName field.

      using System;
      
      // Define a value type that does not override Equals.
      public struct Person
      {
         private string personName;
      
         public Person(string name)
         {
            this.personName = name;
         }
      
         public override string ToString()
         {
            return this.personName;
         }
      }
      
      public struct Example
      {
         public static void Main()
         {
            Person person1 = new Person("John");
            Person person2 = new Person("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.
      Public Structure Person
         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 Example
         Public Sub Main()
            Dim p1 As New Person("John")
            Dim p2 As New Person("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 Framework 中所有類型的基類,因此, Object.Equals(Object) 方法會提供所有其他類型的預設相等比較。Because the Object class is the base class for all types in the .NET Framework, the Object.Equals(Object) method provides the default equality comparison for all other types. 不過,型別通常會覆寫 Equals 方法以實值相等。However, types often override the Equals method to implement value equality. 如需詳細資訊,請參閱呼叫者的備註和繼承者章節的附注。For more information, see the Notes for Callers and Notes for Inheritors sections.

Windows 執行階段的注意事項Notes for the Windows Runtime

當您在 Windows 執行階段的類別上呼叫方法多載時 Equals(Object) ,它會為不會覆寫的類別提供預設行為 Equals(Object)When you call the Equals(Object) method overload on a class in the Windows Runtime, it provides the default behavior for classes that don't override Equals(Object). 這是 .NET Framework 為 Windows 執行階段提供的支援的一部分 (請參閱 .NET Framework 支援 Windows Store 應用程式和 Windows 執行階段) 。This is part of the support that the .NET Framework provides for the Windows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Windows 執行階段中的類別不會繼承 Object ,而且目前不會執行 Equals(Object) 方法。Classes in the Windows Runtime don't inherit Object, and currently don't implement an Equals(Object) method. 但是, ToString Equals(Object) GetHashCode 當您在 c # 或 Visual Basic 程式碼中使用這些方法時,它們看起來會有、和方法,而 .NET Framework 提供這些方法的預設行為。However, they appear to have ToString, Equals(Object), and GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods.

注意

以 c # 或 Visual Basic 撰寫的 Windows 執行階段類別可以覆寫 Equals(Object) 方法多載。Windows Runtime classes that are written in C# or Visual Basic can override the Equals(Object) method overload.

呼叫者注意事項Notes for Callers

衍生類別經常會覆寫 Object.Equals(Object) 方法,以執行實值相等。Derived classes frequently override the Object.Equals(Object) method to implement value equality. 此外,類型也經常會提供額外的強型別多載給 Equals 方法,通常是藉由實作為 IEquatable<T> 介面。In addition, types also frequently provide an additional strongly typed overload to the Equals method, typically by implementing the IEquatable<T> interface. 當您呼叫 Equals 方法來測試是否相等時,您應該知道目前的實例是否會覆寫 Object.Equals ,並瞭解如何解決特定的 Equals 方法呼叫。When you call the Equals method to test for equality, you should know whether the current instance overrides Object.Equals and understand how a particular call to an Equals method is resolved. 否則,您可能執行的測試是否與您想要的相等,而且方法可能會傳回非預期的值。Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value.

下列範例提供說明。The following example provides an illustration. 它會具現化 StringBuilder 具有相同字串的三個物件,然後進行四個 Equals 方法呼叫。It instantiates three StringBuilder objects with identical strings, and then makes four calls to Equals methods. 第一個方法呼叫會傳回 true ,而其餘的三個會傳回 falseThe first method call returns true, and the remaining three return false.

using System;
using System.Text;

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

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

      Object sb3 = new StringBuilder("building a string...");
      Console.WriteLine("\nsb3.Equals(sb2): {0}", 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 Example
   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) ,其會測試值是否相等。In the first case, the strongly typed StringBuilder.Equals(StringBuilder) method overload, which tests for value equality, is called. 因為指派給兩個物件的字串 StringBuilder 相等,所以此方法會傳回 trueBecause the strings assigned to the two StringBuilder objects are equal, the method returns true. 但是,不 StringBuilder 會覆寫 Object.Equals(Object)However, StringBuilder does not override Object.Equals(Object). 因此,當 StringBuilder 物件轉型為時 Object ,當 StringBuilder 實例指派給類型的變數, Object 而且 Object.Equals(Object, Object) 方法傳遞給兩個物件時, StringBuilder Object.Equals(Object) 會呼叫預設方法。Because of this, when the StringBuilder object is cast to an Object, when a StringBuilder instance is assigned to a variable of type Object, and when the Object.Equals(Object, Object) method is passed two StringBuilder objects, the default Object.Equals(Object) method is called. 因為 StringBuilder 是參考型別,所以這相當於將兩個 StringBuilder 物件傳遞給 ReferenceEquals 方法。Because StringBuilder is a reference type, this is equivalent to passing the two StringBuilder objects to the ReferenceEquals method. 雖然這三個 StringBuilder 物件都包含相同的字串,但它們參考三個不同的物件。Although all three StringBuilder objects contain identical strings, they refer to three distinct objects. 因此,這三個方法呼叫會傳回 falseAs a result, these three method calls return false.

您可以藉由呼叫方法,將目前的物件與另一個物件進行參考相等比較 ReferenceEqualsYou can compare the current object to another object for reference equality by calling the ReferenceEquals method. 在 Visual Basic 中,您也可以使用 is 關鍵字 (例如 If Me Is otherObject Then ...) 。In Visual Basic, you can also use the is keyword (for example, If Me Is otherObject Then ...).

繼承者注意事項Notes for Inheritors

當您定義自己的型別時,該型別會繼承 Equals 其基底類型的方法所定義的功能。When you define your own type, that type inherits the functionality defined by the Equals method of its base type. 下表列出 Equals .NET Framework 中類型主要類別的方法的預設執行。The following table lists the default implementation of the Equals method for the major categories of types in the .NET Framework.

型別分類Type category 的相等定義Equality defined by 註解Comments
直接衍生自的類別 ObjectClass derived directly from Object Object.Equals(Object) 參考相等;相當於呼叫 Object.ReferenceEqualsReference equality; equivalent to calling Object.ReferenceEquals.
結構Structure ValueType.Equals 值相等;使用反映,以每個位元組逐一進行的比較或逐欄位比較。Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection.
列舉型別Enumeration Enum.Equals 值必須具有相同的列舉類型和相同的基礎值。Values must have the same enumeration type and the same underlying value.
代理人Delegate MulticastDelegate.Equals 委派的類型必須與相同的調用清單相同。Delegates must have the same type with identical invocation lists.
介面Interface Object.Equals(Object) 參考相等。Reference equality.

針對實值型別,您應該一律覆寫 Equals ,因為依賴反映的相等測試會提供效能不佳。For a value type, you should always override Equals, because tests for equality that rely on reflection offer poor performance. 您也可以覆寫參考型別的預設實 Equals 作為,以測試值是否相等,而不是參考相等,以及定義值相等的精確意義。You can also override the default implementation of Equals for reference types to test for value equality instead of reference equality and to define the precise meaning of value equality. Equals true 如果兩個物件具有相同的值,則會傳回這類傳回,即使它們不是相同的實例。Such implementations of Equals return true if the two objects have the same value, even if they are not the same instance. 型別的實施者會決定物件的值,但它通常是儲存在物件之執行個體變數中的部分或所有資料。The type's implementer decides what constitutes an object's value, but it is typically some or all the data stored in the instance variables of the object. 例如,物件的值是以 String 字串的字元為基礎; String.Equals(Object) 方法會覆寫 Object.Equals(Object) 方法,以 true 針對包含相同順序之相同字元的任何兩個字串實例傳回。For example, the value of a String object is based on the characters of the string; the String.Equals(Object) method overrides the Object.Equals(Object) method to return true for any two string instances that contain the same characters in the same order.

下列範例顯示如何覆寫 Object.Equals(Object) 方法,以測試值是否相等。The following example shows how to override the Object.Equals(Object) method to test for value equality. 它會覆寫 Equals 類別的方法 PersonIt overrides the Equals method for the Person class. 如果 Person 接受其基底類別的相等,則 Person 只有在參考單一物件時,兩個物件才會相等。If Person accepted its base class implementation of equality, two Person objects would be equal only if they referenced a single object. 不過,在這種情況下,如果兩個 Person 物件具有相同的屬性值,就會相等 Person.IdHowever, in this case, two Person objects are equal if they have the same value for the Person.Id property.

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

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

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

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

public class Example
{
   public static void Main()
   {
      Person p1 = new Person("John", "63412895");
      Person p2 = new Person("Jack", "63412895");
      Console.WriteLine(p1.Equals(p2));
      Console.WriteLine(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 Example
   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> 介面,以提供強型別的相等測試。In addition to overriding Equals, you can implement the IEquatable<T> interface to provide a strongly typed test for equality.

下列語句對於方法的所有實值都必須為 true Equals(Object)The following statements must be true for all implementations of the Equals(Object) method. 在清單中, xyz 代表非 null 的物件參考。In the list, x, y, and z represent object references that are not null.

  • x.Equals(x)``true除了牽涉到浮點數類型的案例之外,會傳回。x.Equals(x) returns true, except in cases that involve floating-point types. 請參閱 ISO/IEC/IEEE 60559:2011、資訊技術--微處理器系統--Floating-Point 算術See ISO/IEC/IEEE 60559:2011, Information technology -- Microprocessor Systems -- Floating-Point arithmetic.

  • x.Equals(y) 會傳回與 y.Equals(x) 相同的值。x.Equals(y) returns the same value as y.Equals(x).

  • x.Equals(y)``true如果 xy 都是,則會傳回 NaNx.Equals(y) returns true if both x and y are NaN.

  • 如果 (x.Equals(y) && y.Equals(z)) 傳回 true ,則會傳回 x.Equals(z) trueIf (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.

  • 連續呼叫 x.Equals(y) 會傳回相同的值,但前提 x y 是不會修改和所參考的物件。Successive calls to x.Equals(y) return the same value as long as the objects referenced by x and y are not modified.

  • x.Equals(null) 會傳回 falsex.Equals(null) returns false.

的執行 Equals 不能擲回例外狀況,而應該一律傳回值。Implementations of Equals must not throw exceptions; they should always return a value. 例如,如果 objnull ,則 Equals 應該傳回方法, false 而不是擲回 ArgumentNullExceptionFor example, if obj is null, the Equals method should return false instead of throwing an ArgumentNullException.

覆寫時,請遵循下列指導方針 Equals(Object)Follow these guidelines when overriding Equals(Object):

  • 實作為的類型 IComparable 必須覆寫 Equals(Object)Types that implement IComparable must override Equals(Object).

  • 覆寫的類型 Equals(Object) 也必須覆寫 GetHashCode ; 否則,雜湊表可能無法正常運作。Types that override Equals(Object) must also override GetHashCode; otherwise, hash tables might not work correctly.

  • 您應該考慮執行 IEquatable<T> 介面,以支援強型別測試是否相等。You should consider implementing the IEquatable<T> interface to support strongly typed tests for equality. 您的 IEquatable<T>.Equals 執行應該會傳回與一致的結果 EqualsYour IEquatable<T>.Equals implementation should return results that are consistent with Equals.

  • 如果您的程式設計語言支援運算子多載,且您針對指定的型別多載等號比較運算子,您也必須覆寫方法,以傳回與 Equals(Object) 相等運算子相同的結果。If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override the Equals(Object) method to return the same result as the equality operator. 這有助於確保使用 Equals ((例如) 和)的類別庫程式碼的 ArrayList Hashtable 行為,與應用程式程式碼使用等號比較運算子的方式一致。This helps ensure that class library code that uses Equals (such as ArrayList and Hashtable) behaves in a manner that is consistent with the way the equality operator is used by application code.

參考型別的指導方針Guidelines for Reference Types

下列指導方針適用于覆寫 Equals(Object) 參考型別:The following guidelines apply to overriding Equals(Object) for a reference type:

  • Equals如果類型的語義是以型別代表 (s) 的某個事實為基礎,請考慮覆寫。Consider overriding Equals if the semantics of the type are based on the fact that the type represents some value(s).

  • 大部分的參考型別都不能多載等號比較運算子,即使它們覆寫也一樣 EqualsMost reference types must not overload the equality operator, even if they override Equals. 但是,如果您要執行的引用型別必須是值語義,例如複數型別,則您必須覆寫等號比較運算子。However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator.

  • 您不應該覆寫 Equals 可變參考型別。You should not override Equals on a mutable reference type. 這是因為覆寫 Equals 需要您也覆寫 GetHashCode 方法(如上一節所述)。This is because overriding Equals requires that you also override the GetHashCode method, as discussed in the previous section. 這表示可變動的參考型別之實例的雜湊碼在其存留期內可能會變更,而這可能會導致物件在雜湊表中遺失。This means that the hash code of an instance of a mutable reference type can change during its lifetime, which can cause the object to be lost in a hash table.

實數值型別的指導方針Guidelines for Value Types

下列指導方針適用于覆寫實 Equals(Object) 值型別:The following guidelines apply to overriding Equals(Object) for a value type:

  • 如果您要定義的實值型別包含一或多個值為參考型別的欄位,您應該覆寫 Equals(Object)If you are defining a value type that includes one or more fields whose values are reference types, you should override Equals(Object). Equals(Object)提供的實 ValueType 值會針對其欄位全都是實值型別的實值型別執行逐位元組的比較,但是它會使用反映來對欄位包含參考型別的實值型別進行逐欄位比較。The Equals(Object) implementation provided by ValueType performs a byte-by-byte comparison for value types whose fields are all value types, but it uses reflection to perform a field-by-field comparison of value types whose fields include reference types.

  • 如果您覆寫 Equals 且開發語言支援運算子多載,則必須多載等號比較運算子。If you override Equals and your development language supports operator overloading, you must overload the equality operator.

  • 您應該執行 IEquatable<T> 介面。You should implement the IEquatable<T> interface. 呼叫強型別 IEquatable<T>.Equals 方法可避免將 obj 引數裝箱。Calling the strongly typed IEquatable<T>.Equals method avoids boxing the obj argument.

另請參閱

適用於

Equals(Object, Object)

判斷指定的物件執行個體是否視為相等。Determines whether the specified object instances are considered equal.

public:
 static bool Equals(System::Object ^ objA, System::Object ^ objB);
public static bool Equals (object objA, object objB);
public static bool Equals (object? objA, object? objB);
static member Equals : obj * obj -> bool
Public Shared Function Equals (objA As Object, objB As Object) As Boolean

參數

objA
Object

要比較的第一個物件。The first object to compare.

objB
Object

要比較的第二個物件。The second object to compare.

傳回

Boolean

如果物件可視為相等則為 true,否則為 falsetrue if the objects are considered equal; otherwise, false. 如果 objAobjB 都是 null,則這個方法會傳回 trueIf both objA and objB are null, the method returns true.

範例

下列範例說明 Equals(Object, Object) 方法,並將它與方法進行比較 ReferenceEqualsThe following example illustrates the Equals(Object, Object) method and compares it with the ReferenceEquals method.

using System;

public class Example
{
   public static void Main()
   {
      Dog m1 = new Dog("Alaskan Malamute");
      Dog m2 = new Dog("Alaskan Malamute");
      Dog g1 = new Dog("Great Pyrenees");
      Dog g2 = g1;
      Dog d1 = new Dog("Dalmation");
      Dog n1 = null;
      Dog n2 = null;

      Console.WriteLine("null = null: {0}", Object.Equals(n1, n2));
      Console.WriteLine("null Reference Equals null: {0}\n", Object.ReferenceEquals(n1, n2));

      Console.WriteLine("{0} = {1}: {2}", g1, g2, Object.Equals(g1, g2));
      Console.WriteLine("{0} Reference Equals {1}: {2}\n", g1, g2, Object.ReferenceEquals(g1, g2));

      Console.WriteLine("{0} = {1}: {2}", m1, m2, Object.Equals(m1, m2));
      Console.WriteLine("{0} Reference Equals {1}: {2}\n", m1, m2, Object.ReferenceEquals(m1, m2));

      Console.WriteLine("{0} = {1}: {2}", m1, d1, Object.Equals(m1, d1));
      Console.WriteLine("{0} Reference Equals {1}: {2}", m1, d1, Object.ReferenceEquals(m1, d1));
   }
}

public class Dog
{
   // Public field.
   public string Breed;

   // Class constructor.
   public Dog(string dogBreed)
   {
      this.Breed = dogBreed;
   }

   public override bool Equals(Object obj)
   {
      if (obj == null || !(obj is Dog))
         return false;
      else
         return this.Breed == ((Dog) obj).Breed;
   }

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

   public override string ToString()
   {
      return this.Breed;
   }
}
// The example displays the following output:
//       null = null: True
//       null Reference Equals null: True
//
//       Great Pyrenees = Great Pyrenees: True
//       Great Pyrenees Reference Equals Great Pyrenees: True
//
//       Alaskan Malamute = Alaskan Malamute: True
//       Alaskan Malamute Reference Equals Alaskan Malamute: False
//
//       Alaskan Malamute = Dalmation: False
//       Alaskan Malamute Reference Equals Dalmation: False
Module Example
   Public Sub Main()
      Dim m1 As New Dog("Alaskan Malamute")
      Dim m2 As New Dog("Alaskan Malamute")
      Dim g1 As New Dog("Great Pyrenees")
      Dim g2 As Dog = g1
      Dim d1 As New Dog("Dalmation")
      Dim n1 As Dog = Nothing
      Dim n2 As Dog = Nothing
      
      Console.WriteLine("null = null: {0}", Object.Equals(n1, n2))
      Console.WriteLine("null Reference Equals null: {0}", Object.ReferenceEquals(n1, n2))
      Console.WriteLine()
      
      Console.WriteLine("{0} = {1}: {2}", g1, g2, Object.Equals(g1, g2))
      Console.WriteLine("{0} Reference Equals {1}: {2}", g1, g2, Object.ReferenceEquals(g1, g2))
      Console.WriteLine()
      
      Console.WriteLine("{0} = {1}: {2}", m1, m2, Object.Equals(m1, m2))
      Console.WriteLine("{0} Reference Equals {1}: {2}", m1, m2, Object.ReferenceEquals(m1, m2))
      Console.WriteLine()
      
      Console.WriteLine("{0} = {1}: {2}", m1, d1, Object.Equals(m1, d1))  
      Console.WriteLine("{0} Reference Equals {1}: {2}", m1, d1, Object.ReferenceEquals(m1, d1))  
   End Sub
End Module

Public Class Dog
   ' Public field.
   Public Breed As String
   
   ' Class constructor.
   Public Sub New(dogBreed As String)
      Me.Breed = dogBreed
   End Sub

   Public Overrides Function Equals(obj As Object) As Boolean
      If obj Is Nothing OrElse Not typeof obj Is Dog Then
         Return False
      Else
         Return Me.Breed = CType(obj, Dog).Breed
      End If   
   End Function
   
   Public Overrides Function GetHashCode() As Integer
      Return Me.Breed.GetHashCode()
   End Function
   
   Public Overrides Function ToString() As String
      Return Me.Breed
   End Function
End Class
' The example displays the following output:
'       null = null: True
'       null Reference Equals null: True
'       
'       Great Pyrenees = Great Pyrenees: True
'       Great Pyrenees Reference Equals Great Pyrenees: True
'       
'       Alaskan Malamute = Alaskan Malamute: True
'       Alaskan Malamute Reference Equals Alaskan Malamute: False
'       
'       Alaskan Malamute = Dalmation: False
'       Alaskan Malamute Reference Equals Dalmation: False

備註

靜態 Equals(Object, Object) 方法會指出兩個物件是否 objA objB 相等。The static Equals(Object, Object) method indicates whether two objects, objA and objB, are equal. 它也可讓您測試其值為 null 的物件是否相等。It also enables you to test objects whose value is null for equality. 它會比較 objAobjB 是否相等,如下所示:It compares objA and objB for equality as follows:

  • 它會判斷兩個物件是否代表相同的物件參考。It determines whether the two objects represent the same object reference. 如果有的話,方法會傳回 trueIf they do, the method returns true. 這項測試相當於呼叫 ReferenceEquals 方法。This test is equivalent to calling the ReferenceEquals method. 此外,如果 objAobjB 都是 null,則方法會傳回 trueIn addition, if both objA and objB are null, the method returns true.

  • 它會判斷 objA 或是否 objBnullIt determines whether either objA or objB is null. 如果是,則會傳回 falseIf so, it returns false.

  • 如果兩個物件不代表相同的物件參考,而且不是 null,則會呼叫 objAEquals (objB) 並傳回結果。If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result. 這表示,如果 objA 覆寫 Object.Equals(Object) 方法,則會呼叫此覆寫。This means that if objA overrides the Object.Equals(Object) method, this override is called.

另請參閱

適用於