Object.Equals Object.Equals Object.Equals Object.Equals Method

Definición

Determina si dos instancias de objeto son iguales.Determines whether two object instances are equal.

Sobrecargas

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

Equals(Object, Object) Equals(Object, Object) Equals(Object, Object) Equals(Object, Object)

Determina si las instancias del objeto especificado se consideran iguales.Determines whether the specified object instances are considered equal.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

public:
 virtual bool Equals(System::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

Parámetros

obj
Object Object Object Object

Objeto que se va a comparar con el objeto actual.The object to compare with the current object.

Devoluciones

Es true si el objeto especificado es igual al objeto actual; en caso contrario, es false.true if the specified object is equal to the current object; otherwise, false.

Ejemplos

El ejemplo siguiente se muestra un Point clase que invalide la Equals método para proporcionar la igualdad de valores y un Point3D clase que se deriva de Point.The following example shows a Point class that overrides the Equals method to provide value equality, and a Point3D class that is derived from Point. Dado que Point invalida Object.Equals(Object) para comprobar la igualdad de valores, el Object.Equals(Object) no se llama al método.Because Point overrides Object.Equals(Object) to test for value equality, the Object.Equals(Object) method is not called. Sin embargo, Point3D.Equals llamadas Point.Equals porque Point implementa Object.Equals(Object) en un modo que ofrezca igualdad de valores.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

El Point.Equals método comprueba para asegurarse de que el obj argumento no es null que hace referencia a una instancia del mismo tipo que este objeto.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. Si hay alguna comprobación se produce un error, el método devuelve false.If either check fails, the method returns false.

El Point.Equals llamadas al método el GetType método para determinar si los tipos de tiempo de ejecución de los dos objetos son idénticos.The Point.Equals method calls the GetType method to determine whether the run-time types of the two objects are identical. Si el método utiliza una comprobación del formulario obj is Point en C# o TryCast(obj, Point) en Visual Basic, la comprobación devolverá true en casos donde obj es una instancia de una clase derivada de Point, aunque obj y actual instancia no son del mismo tipo de tiempo de ejecución.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. Después de comprobar que ambos objetos son del mismo tipo, el método convierte obj escriba Point y devuelve el resultado de la comparación de los campos de instancia de los dos objetos.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.

En Point3D.Equals, heredadas Point.Equals método, lo que invalida Object.Equals(Object), se invoca antes de realiza cualquier otra cosa.In Point3D.Equals, the inherited Point.Equals method, which overrides Object.Equals(Object), is invoked before anything else is done. Dado que Point3D es una clase sealed (NotInheritable en Visual Basic), una comprobación en el formulario obj is Point en C# o TryCast(obj, Point) en Visual Basic es la adecuada para asegurarse de que obj es un Point3D objeto.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. Si es un Point3D objeto, se convierte en un Point de objetos y pasa a la implementación de clase base Equals.If it is a Point3D object, it is cast to a Point object and passed to the base class implementation of Equals. Solo cuando el heredado Point.Equals devuelve del método true el método de comparación la z introducidos en la clase derivada de campos de instancia.Only when the inherited Point.Equals method returns true does the method compare the z instance fields introduced in the derived class.

En el ejemplo siguiente se define un Rectangle clase que implementa internamente un rectángulo como dos Point objetos.The following example defines a Rectangle class that internally implements a rectangle as two Point objects. El Rectangle también clase invalidaciones Object.Equals(Object) para proporcionar la igualdad de valores.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

Algunos lenguajes como C# y Visual Basic admiten la sobrecarga de operadores.Some languages such as C# and Visual Basic support operator overloading. Cuando un tipo sobrecarga el operador de igualdad, también debe invalidar el Equals(Object) método para proporcionar la misma funcionalidad.When a type overloads the equality operator, it must also override the Equals(Object) method to provide the same functionality. Normalmente, esto se logra escribiendo el Equals(Object) método en términos del operador de igualdad sobrecargado, como en el ejemplo siguiente.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

Dado que Complex es un tipo de valor, no se pueden derivar.Because Complex is a value type, it cannot be derived from. Por lo tanto, la invalidación Equals(Object) no necesita llamar al método GetType para determinar el tiempo de ejecución preciso escriba de cada objeto, pero en su lugar, use el is operador en C# o la TypeOf operador en Visual Basic para comprobar el tipo de la obj parámetro.Therefore, 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.

Comentarios

El tipo de comparación entre la instancia actual y el obj parámetro depende de si la instancia actual es un tipo de referencia o un tipo de valor.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.

  • Si la instancia actual es un tipo de referencia, el Equals(Object) método comprueba la igualdad de referencia y una llamada a la Equals(Object) es equivalente a una llamada al método el ReferenceEquals método.If 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. Igualdad de referencia significa que las variables de objeto que se comparan hacen referencia al mismo objeto.Reference equality means that the object variables that are compared refer to the same object. El ejemplo siguiente muestra el resultado de una comparación de este tipo.The following example illustrates the result of such a comparison. Define un Person (clase), que es un tipo de referencia, y llama a la Person constructor de clase para crear dos instancias nuevo Person objetos, person1a y person2, que tienen el mismo valor.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. También asigna person1a a otra variable de objeto, person1b.It also assigns person1a to another object variable, person1b. Como se muestra en el ejemplo, la salida person1a y person1b son iguales porque hacen referencia al mismo objeto.As the output from the example shows, person1a and person1b are equal because they reference the same object. Sin embargo, person1a y person2 no son iguales, aunque tienen el mismo valor.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
    
  • Si la instancia actual es un tipo de valor, el Equals(Object) método comprueba la igualdad de valor.If the current instance is a value type, the Equals(Object) method tests for value equality. Igualdad de valores significa lo siguiente:Value equality means the following:

    • Los dos objetos son del mismo tipo.The two objects are of the same type. Como se muestra en el ejemplo siguiente, un Byte no es igual que el objeto que tiene un valor de 12 una Int32 objeto que tiene un valor de 12, porque los dos objetos tienen distintos tipos de tiempo de ejecución.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.

      using System;
      
      public class Example
      {
         public static void Main()
         {
            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
      
    • Los valores de los campos públicos y privados de los dos objetos son iguales.The values of the public and private fields of the two objects are equal. El ejemplo siguiente se comprueba la igualdad de valor.The following example tests for value equality. Define un Person estructura, que es un tipo de valor, y llama a la Person constructor de clase para crear dos instancias nuevo Person objetos, person1 y person2, que tienen el mismo valor.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. Como se muestra el resultado del ejemplo, aunque las dos variables de objeto hacen referencia a objetos diferentes, person1 y person2 son iguales porque tienen el mismo valor para la privada personName campo.As 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
      

Dado que el Object clase es la clase base para todos los tipos en .NET Framework, el Object.Equals(Object) método proporciona la comparación de igualdad predeterminado para todos los demás tipos.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. Sin embargo, los tipos a menudo invalidar el Equals método para implementar la igualdad de valores.However, types often override the Equals method to implement value equality. Para obtener más información, vea las notas para los autores de llamadas y notas de las secciones de los herederos.For more information, see the Notes for Callers and Notes for Inheritors sections.

Notas de la Windows en tiempo de ejecuciónWindows RuntimeNotes for the Windows en tiempo de ejecuciónWindows Runtime

Cuando se llama a la Equals(Object) sobrecarga del método en una clase de la Windows en tiempo de ejecuciónWindows Runtime, proporciona el comportamiento predeterminado para las clases que no se invalidan Equals(Object).When you call the Equals(Object) method overload on a class in the Windows en tiempo de ejecuciónWindows Runtime, it provides the default behavior for classes that don't override Equals(Object). Esto forma parte de la compatibilidad que .NET Framework proporciona para el Windows en tiempo de ejecuciónWindows Runtime (consulte soporte técnico para Windows Store aplicaciones de .NET Framework y Windows Runtime).This is part of the support that the .NET Framework provides for the Windows en tiempo de ejecuciónWindows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Las clases en el Windows en tiempo de ejecuciónWindows Runtime no heredar Objecty actualmente no se implementa un Equals(Object) método.Classes in the Windows en tiempo de ejecuciónWindows Runtime don't inherit Object, and currently don't implement an Equals(Object) method. Sin embargo, parece que tienen ToString, Equals(Object), y GetHashCode métodos al usarlos en el código de C# o Visual Basic y .NET Framework proporciona el comportamiento predeterminado de estos métodos.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.

Nota

Windows en tiempo de ejecuciónWindows Runtime las clases que se escriben en C# o Visual Basic pueden reemplazar el Equals(Object) sobrecarga del método.classes that are written in C# or Visual Basic can override the Equals(Object) method overload.

Notas para los llamadoresNotes for Callers

Las clases derivadas reemplazan con frecuencia el Object.Equals(Object) método para implementar la igualdad de valores.Derived classes frequently override the Object.Equals(Object) method to implement value equality. Además, los tipos también suelen ofrecen una sobrecarga adicional fuertemente tipada para el Equals método, normalmente mediante la implementación de la IEquatable<T> interfaz.In addition, types also frequently provide an additional strongly typed overload to the Equals method, typically by implementing the IEquatable<T> interface. Cuando se llama a la Equals método para comprobar la igualdad, debe saber si se reemplaza la instancia actual Object.Equals y entender cómo una determinada llamada a un Equals método se ha resuelto.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. En caso contrario, es posible que se realice una prueba de igualdad que es diferente de los previstos, y el método puede devolver un valor inesperado.Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value.

Esto se muestra en el ejemplo siguiente.The following example provides an illustration. Crea una instancia de tres StringBuilder objetos con cadenas idénticas y, a continuación, realiza cuatro llamadas a Equals métodos.It instantiates three StringBuilder objects with identical strings, and then makes four calls to Equals methods. La primera llamada al método devuelve truey la devolución de tres restantes false.The 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

En el primer caso, fuertemente tipado StringBuilder.Equals(StringBuilder) sobrecarga del método, que comprueba la igualdad de valor, se llama.In the first case, the strongly typed StringBuilder.Equals(StringBuilder) method overload, which tests for value equality, is called. Dado que las cadenas se asigna a los dos StringBuilder objetos son iguales, el método devuelve true.Because the strings assigned to the two StringBuilder objects are equal, the method returns true. Sin embargo, StringBuilder no invalida Object.Equals(Object).However, StringBuilder does not override Object.Equals(Object). Por este motivo, cuando el StringBuilder objeto se convierte en un Object, cuando un StringBuilder instancia se asigna a una variable de tipo Objecty cuándo el Object.Equals(Object, Object) se pasa al método dos StringBuilder objetos, el valor predeterminado Object.Equals(Object)se llama al método.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. Dado que StringBuilder es un tipo de referencia, esto es equivalente a pasar los dos StringBuilder objetos a la ReferenceEquals método.Because StringBuilder is a reference type, this is equivalent to passing the two StringBuilder objects to the ReferenceEquals method. Aunque las tres StringBuilder objetos contienen cadenas idénticas, hacen referencia a tres objetos diferenciados.Although all three StringBuilder objects contain identical strings, they refer to three distinct objects. Como resultado, estos tres métodos llama devuelto false.As a result, these three method calls return false.

Puede comparar el objeto actual con otro objeto para la igualdad de referencia mediante una llamada a la ReferenceEquals método.You can compare the current object to another object for reference equality by calling the ReferenceEquals method. En Visual Basic, también puede usar el is palabra clave (por ejemplo, If Me Is otherObject Then ...).In Visual Basic, you can also use the is keyword (for example, If Me Is otherObject Then ...).

Notas para los herederosNotes for Inheritors

Al definir su propio tipo, ese tipo hereda la funcionalidad definida por el Equals método de su tipo base.When you define your own type, that type inherits the functionality defined by the Equals method of its base type. La tabla siguiente muestra la implementación predeterminada de la Equals método para las principales categorías de tipos en .NET Framework.The following table lists the default implementation of the Equals method for the major categories of types in the .NET Framework.

Categoría de tipoType category Igualdad definido porEquality defined by ComentariosComments
Clase se deriva directamente ObjectClass derived directly from Object Object.Equals(Object) Igualdad de referencia; equivalente a llamar a Object.ReferenceEquals.Reference equality; equivalent to calling Object.ReferenceEquals.
EstructuraStructure ValueType.Equals Igualdad de valor; comparación byte a byte directa o bien mediante la reflexión de comparación de campo por campo.Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection.
EnumeraciónEnumeration Enum.Equals Valores deben tener el mismo tipo de enumeración y el mismo valor subyacente.Values must have the same enumeration type and the same underlying value.
DelegadoDelegate MulticastDelegate.Equals Los delegados deben tener el mismo tipo con listas de invocación idénticos.Delegates must have the same type with identical invocation lists.
InterfazInterface Object.Equals(Object) Igualdad de referencia.Reference equality.

Para un tipo de valor, debe invalidar siempre Equals, ya que comprueba la igualdad que se basan en la reflexión ofrece un rendimiento deficiente.For a value type, you should always override Equals, because tests for equality that rely on reflection offer poor performance. También puede invalidar la implementación predeterminada de Equals para tipos de referencia para comprobar la igualdad de valor en lugar de igualdad de referencia y para definir el significado exacto de la igualdad de valores.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. Este tipo de implementaciones de Equals devolver true si los dos objetos tienen el mismo valor, aunque no sean la misma instancia.Such implementations of Equals return true if the two objects have the same value, even if they are not the same instance. El implementador de tipos decide lo que constituye el valor de un objeto, pero suele ser algunos o todos los datos almacenados en las variables de instancia del objeto.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. Por ejemplo, el valor de un String objeto se basa en los caracteres de la cadena; la String.Equals(Object) reemplazos de método la Object.Equals(Object) método devuelva true para cualquier dos instancias que contienen los mismos caracteres en el mismo orden de cadena.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.

El ejemplo siguiente muestra cómo invalidar el Object.Equals(Object) método para comprobar la igualdad de valores.The following example shows how to override the Object.Equals(Object) method to test for value equality. Invalida el Equals método para el Person clase.It overrides the Equals method for the Person class. Si Person aceptado su implementación de la clase base de la igualdad de dos Person objetos serían iguales solo si hace referencia a un único objeto.If Person accepted its base class implementation of equality, two Person objects would be equal only if they referenced a single object. Sin embargo, en este caso, dos Person objetos son iguales si tienen el mismo valor para el Person.Id propiedad.However, 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

Además de invalidar Equals, puede implementar el IEquatable<T> interfaz para proporcionar una prueba de igualdad fuertemente tipada.In addition to overriding Equals, you can implement the IEquatable<T> interface to provide a strongly typed test for equality.

Deben cumplirse las siguientes instrucciones para todas las implementaciones de la Equals(Object) método.The following statements must be true for all implementations of the Equals(Object) method. En la lista, x, y, y z representan las referencias de objeto que no sean null.In the list, x, y, and z represent object references that are not null.

  • x.Equals(x) Devuelve true, excepto en los casos que implican tipos de punto flotante.x.Equals(x) returns true, except in cases that involve floating-point types. Vea ISO/IEC/IEEE 60559:2011, tecnología de la información--microprocesador sistemas--aritmética de punto flotante.See ISO/IEC/IEEE 60559:2011, Information technology -- Microprocessor Systems -- Floating-Point arithmetic.

  • x.Equals(y) devuelve el mismo valor que y.Equals(x).x.Equals(y) returns the same value as y.Equals(x).

  • x.Equals(y) Devuelve true si ambos x y y son NaN.x.Equals(y) returns true if both x and y are NaN.

  • Si (x.Equals(y) && y.Equals(z)) devuelve true, a continuación, x.Equals(z) devuelve true.If (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.

  • Las llamadas sucesivas a x.Equals(y) devuelven el mismo valor siempre y cuando los objetos al que hace referencia x y y no se modifican.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) devuelve false.x.Equals(null) returns false.

Las implementaciones de Equals no deben producir excepciones; siempre debe devolver un valor.Implementations of Equals must not throw exceptions; they should always return a value. Por ejemplo, si obj es null, Equals método debe devolver false en lugar de producir una ArgumentNullException.For example, if obj is null, the Equals method should return false instead of throwing an ArgumentNullException.

Siga estas instrucciones cuando se reemplaza Equals(Object):Follow these guidelines when overriding Equals(Object):

  • Los tipos que implementan IComparable debe invalidar Equals(Object).Types that implement IComparable must override Equals(Object).

  • Los tipos que reemplazan Equals(Object) también debe invalidar GetHashCode; de lo contrario, las tablas hash no funcionen correctamente.Types that override Equals(Object) must also override GetHashCode; otherwise, hash tables might not work correctly.

  • Debe considerar implementar la IEquatable<T> interfaz para admitir fuertemente tipados comprueba la igualdad.You should consider implementing the IEquatable<T> interface to support strongly typed tests for equality. Su IEquatable<T>.Equals implementación debería devolver los resultados que sean coherentes con Equals.Your IEquatable<T>.Equals implementation should return results that are consistent with Equals.

  • Si su lenguaje de programación admite la sobrecarga de operadores y sobrecargar el operador de igualdad para un tipo determinado, también debe invalidar el Equals(Object) método para devolver el mismo resultado que el operador de igualdad.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. Esto ayuda a garantizar ese código de biblioteca de clases que utiliza Equals (como ArrayList y Hashtable) se comporta de forma que sea coherente con la manera en que se usa el operador de igualdad por código de aplicación.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.

Directrices para los tipos de referenciaGuidelines for Reference Types

Las siguientes directrices se aplican a reemplazar Equals(Object) para un tipo de referencia:The following guidelines apply to overriding Equals(Object) for a reference type:

  • Considere la posibilidad de invalidar Equals si la semántica del tipo se basa en el hecho de que el tipo representa algunos valores.Consider overriding Equals if the semantics of the type are based on the fact that the type represents some value(s).

  • La mayoría de los tipos de referencia no deben sobrecargar el operador de igualdad, aunque reemplacen Equals.Most reference types must not overload the equality operator, even if they override Equals. Sin embargo, si está implementando un tipo de referencia que pretende tener semántica de valor, como un tipo de número complejo, debe reemplazar el operador de igualdad.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.

  • No se debe reemplazar Equals en un tipo de referencia mutable.You should not override Equals on a mutable reference type. Esto es porque reemplazar Equals requiere que invalide también el GetHashCode método, como se describe en la sección anterior.This is because overriding Equals requires that you also override the GetHashCode method, as discussed in the previous section. Esto significa que puede cambiar el código hash de una instancia de un tipo de referencia mutable durante su vigencia, lo que puede producir el objeto se perderá en una tabla hash.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.

Directrices para los tipos de valorGuidelines for Value Types

Las siguientes directrices se aplican a reemplazar Equals(Object) para un tipo de valor:The following guidelines apply to overriding Equals(Object) for a value type:

  • Si va a definir un tipo de valor que incluye uno o más campos cuyos valores son tipos de referencia, debe reemplazar 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). El Equals(Object) implementación proporcionada por ValueType realiza una comparación byte a byte para tipos de valor cuyos campos son todos los tipos de valor, pero usa la reflexión para realizar una comparación de campo por campo de tipos de valor cuyos campos incluyen tipos de referencia.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.

  • Si invalida Equals y el lenguaje de programación admite la sobrecarga de operadores, debe sobrecargar el operador de igualdad.If you override Equals and your development language supports operator overloading, you must overload the equality operator.

  • Debe implementar la IEquatable<T> interfaz.You should implement the IEquatable<T> interface. Una llamada a fuertemente tipado IEquatable<T>.Equals método impide la conversión boxing el obj argumento.Calling the strongly typed IEquatable<T>.Equals method avoids boxing the obj argument.

Consulte también:

Equals(Object, Object) Equals(Object, Object) Equals(Object, Object) Equals(Object, Object)

Determina si las instancias del objeto especificado se consideran iguales.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);
static member Equals : obj * obj -> bool
Public Shared Function Equals (objA As Object, objB As Object) As Boolean

Parámetros

objA
Object Object Object Object

Primer objeto que se va a comparar.The first object to compare.

objB
Object Object Object Object

Segundo objeto que se va a comparar.The second object to compare.

Devoluciones

Es true si los dos objetos se consideran iguales; en caso contrario, es false.true if the objects are considered equal; otherwise, false. Si tanto objA como objB son null, el método devuelve true.If both objA and objB are null, the method returns true.

Ejemplos

El ejemplo siguiente ilustra la Equals(Object, Object) método y lo compara con el ReferenceEquals método.The 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

Comentarios

Estático Equals(Object, Object) método indica si dos objetos, objA y objB, son iguales.The static Equals(Object, Object) method indicates whether two objects, objA and objB, are equal. También permite probar los objetos cuyo valor es null igualdad.It also enables you to test objects whose value is null for equality. Compara objA y objB igualdad como sigue:It compares objA and objB for equality as follows:

  • Determina si los dos objetos representan la misma referencia de objeto.It determines whether the two objects represent the same object reference. Si es así, el método devuelve true.If they do, the method returns true. Esta prueba es equivalente a llamar a la ReferenceEquals método.This test is equivalent to calling the ReferenceEquals method. Además, si ambos objA y objB son null, el método devuelve true.In addition, if both objA and objB are null, the method returns true.

  • Determina si ya sea objA o objB es null.It determines whether either objA or objB is null. Si es así, devuelve false.If so, it returns false.

  • Si los dos objetos no representan la misma referencia de objeto y ninguna de ellas es null, llama a objA.Equals (objB) y devuelve el resultado.If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result. Esto significa que si objA invalida la Object.Equals(Object) , esta invalidación se llama al método.This means that if objA overrides the Object.Equals(Object) method, this override is called.

Consulte también:

Se aplica a