Object.Equals Método

Definición

Determina si dos instancias de objeto son iguales.

Sobrecargas

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

Equals(Object, Object)

Determina si las instancias del objeto especificado se consideran iguales.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

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

Parámetros

obj
Object

Objeto que se va a comparar con el objeto actual.

Devoluciones

Boolean

true si el objeto especificado es igual al objeto actual; en caso contrario, false.

Ejemplos

En el ejemplo siguiente se muestra una Point clase que invalida el Equals método para proporcionar igualdad de valores y una Point3D clase derivada de Point. Dado que Point invalida Object.Equals(Object) para probar la igualdad de valores, no se llama al Object.Equals(Object) método . Sin embargo, Point3D.Equals llama a Point.Equals porque Point implementa Object.Equals(Object) de una manera que proporciona igualdad de valores.

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
type Point(x, y) =
    new () = Point(0, 0)
    member _.X = x
    member _.Y = y

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

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

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

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

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

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

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

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

printfn $"{point2D} = {point3Da}: {point2D.Equals point3Da}"
printfn $"{point2D} = {point3Db}: {point2D.Equals point3Db}"
printfn $"{point3Da} = {point3Db}: {point3Da.Equals point3Db}"
printfn $"{point3Da} = {point3Dc}: {point3Da.Equals point3Dc}"
// The example displays the following output:
//       Point(5, 5) = Point(5, 5, 2): False
//       Point(5, 5) = Point(5, 5, 2): False
//       Point(5, 5, 2) = Point(5, 5, 2): True
//       Point(5, 5, 2) = Point(5, 5, -1): False
Class 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 que el obj argumento no es NULL y que hace referencia a una instancia del mismo tipo que este objeto. Si se produce un error en cualquiera de las comprobaciones, el método devuelve false.

El Point.Equals método llama al GetType método para determinar si los tipos en tiempo de ejecución de los dos objetos son idénticos. Si el método usó una comprobación del formulario obj is Point en C# o TryCast(obj, Point) en Visual Basic, la comprobación devolvería true en casos en obj los que es una instancia de una clase derivada de Point, aunque obj y la instancia actual no sean del mismo tipo de tiempo de ejecución. Después de comprobar que ambos objetos son del mismo tipo, el método convierte obj al tipo Point y devuelve el resultado de comparar los campos de instancia de los dos objetos.

En Point3D.Equals, el método heredado Point.Equals , que invalida Object.Equals(Object), se invoca antes de que se haga cualquier otra cosa. Dado Point3D que es una clase sellada (NotInheritable en Visual Basic), una comprobación en el formulario obj is Point en C# o TryCast(obj, Point) en Visual Basic es adecuada para asegurarse de que obj es un Point3D objeto . Si es un Point3D objeto , se convierte en un Point objeto y se pasa a la implementación de clase base de Equals. Solo cuando el método heredado Point.Equals devuelve true hace que el método compare los z campos de instancia introducidos en la clase derivada.

En el ejemplo siguiente se define una Rectangle clase que implementa internamente un rectángulo como dos Point objetos. La Rectangle clase también invalida Object.Equals(Object) para proporcionar igualdad de valores.

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
type Point(x, y) =
    member _.X = x
    member _.Y = y

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

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

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

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

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

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

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

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

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

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

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

Algunos lenguajes como C# y Visual Basic admiten la sobrecarga del operador. Cuando un tipo sobrecarga el operador de igualdad, también debe invalidar el Equals(Object) método para proporcionar la misma funcionalidad. Normalmente, esto se logra escribiendo el Equals(Object) método en términos del operador de igualdad sobrecargado, como en el ejemplo siguiente.

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
[<Struct; CustomEquality; NoComparison>]
type Complex =
    val mutable re: double
    val mutable im: double

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

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

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

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

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

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

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

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

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

cmplx2.re <- 4.0

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

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

Class 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 Complex que es un tipo de valor, no se puede derivar de . Por lo tanto, la invalidación del Equals(Object) método no necesita llamar GetType a para determinar el tipo de tiempo de ejecución preciso de cada objeto, pero puede usar el is operador en C# o el TypeOf operador de Visual Basic para comprobar el tipo del obj parámetro.

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.

  • Si la instancia actual es un tipo de referencia, el Equals(Object) método comprueba la igualdad de referencia y una llamada al Equals(Object) método es equivalente a una llamada al ReferenceEquals método . La igualdad de referencia significa que las variables de objeto que se comparan hacen referencia al mismo objeto. En el ejemplo siguiente se muestra el resultado de esta comparación. Define una clase, que es un tipo de referencia, y llama al Person constructor de clase para crear una Person instancia de dos objetos nuevosPerson, person1a y person2, que tienen el mismo valor. También se person1a asigna a otra variable de objeto, person1b. Como se muestra en la salida del ejemplo, person1a y person1b son iguales porque hacen referencia al mismo objeto. Sin embargo, person1a y person2 no son iguales, aunque tienen el mismo valor.

    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.
    type Person(name) =
        override _.ToString() =
            name
    
    let person1a = Person "John"
    let person1b = person1a
    let person2 = Person(string person1a)
    
    printfn "Calling Equals:"
    printfn $"person1a and person1b: {person1a.Equals person1b}"
    printfn $"person1a and person2: {person1a.Equals person2}"
    
    printfn "\nCasting to an Object and calling Equals:"
    printfn $"person1a and person1b: {(person1a :> obj).Equals(person1b :> obj)}"
    printfn $"person1a and person2: {(person1a :> obj).Equals(person2 :> obj)}"
    // The example displays the following output:
    //       person1a and person1b: True
    //       person1a and person2: False
    //
    //       Casting to an Object and calling Equals:
    //       person1a and person1b: True
    //       person1a and person2: False
    
    ' Define a reference type that does not override Equals.
    Public Class 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 valores. La igualdad de valores significa lo siguiente:

    • Los dos objetos son del mismo tipo. Como se muestra en el ejemplo siguiente, un Byte objeto que tiene un valor de 12 no es igual a un Int32 objeto que tiene un valor de 12, porque los dos objetos tienen tipos de tiempo de ejecución diferentes.

      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
      
      let value1 = 12uy
      let value2 = 12
      
      let object1 = value1 :> obj
      let object2 = value2 :> obj
      
      printfn $"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals object2}"
      
      // The example displays the following output:
      //        12 (Byte) = 12 (Int32): False
      
      Module 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úblico y privado de los dos objetos son iguales. En el ejemplo siguiente se comprueba la igualdad de valores. Define una estructura, que es un tipo de valor, y llama al Person constructor de clase para crear una Person instancia de dos objetos nuevosPerson, person1 y person2, que tienen el mismo valor. Como se muestra en la salida del ejemplo, aunque las dos variables de objeto hacen referencia a objetos person1 diferentes y person2 son iguales porque tienen el mismo valor para el campo privado personName .

      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.
      [<Struct>]
      type Person(personName: string) =
          override _.ToString() =
              personName
      
      let person1 = Person "John"
      let person2 = Person "John"
      
      printfn "Calling Equals:"
      printfn $"{person1.Equals person2}"
      
      printfn $"\nCasting to an Object and calling Equals:"
      printfn $"{(person1 :> obj).Equals(person2 :> obj)}"
      // The example displays the following output:
      //       Calling Equals:
      //       True
      //
      //       Casting to an Object and calling Equals:
      //       True
      
      ' Define a value type that does not override Equals.
      Public Structure 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 la Object clase es la clase base para todos los tipos de la .NET Framework, el Object.Equals(Object) método proporciona la comparación de igualdad predeterminada para todos los demás tipos. Sin embargo, los tipos suelen invalidar el método para implementar la Equals igualdad de valores. Para obtener más información, vea las secciones Notes for Callers y Notes for Inheritors .

Notas de la Windows Runtime

Cuando se llama a la sobrecarga del Equals(Object) método en una clase de la Windows Runtime, proporciona el comportamiento predeterminado para las clases que no invalidan Equals(Object). Esto forma parte de la compatibilidad que proporciona el .NET Framework para el Windows Runtime (consulta .NET Framework soporte técnico para aplicaciones y Windows Runtime de la Tienda Windows). Las clases del Windows Runtime no heredan Objecty actualmente no implementan un Equals(Object) método . Sin embargo, parecen tener ToStringmétodos , Equals(Object)y GetHashCode cuando los usa en el código de C# o Visual Basic, y el .NET Framework proporciona el comportamiento predeterminado para estos métodos.

Nota

Windows Runtime clases escritas en C# o Visual Basic pueden invalidar la sobrecarga del Equals(Object) método.

Notas de los autores de llamadas

Las clases derivadas invalidan con frecuencia el método para implementar la Object.Equals(Object) igualdad de valores. Además, los tipos también suelen proporcionar una sobrecarga fuertemente tipada adicional al Equals método , normalmente mediante la implementación de la IEquatable<T> interfaz . Al llamar al Equals método para probar la igualdad, debe saber si la instancia actual invalida Object.Equals y comprende cómo se resuelve una llamada determinada a un Equals método. De lo contrario, es posible que esté realizando una prueba de igualdad que sea diferente de la prevista y que el método pueda devolver un valor inesperado.

Esto se muestra en el ejemplo siguiente. Crea una instancia de tres StringBuilder objetos con cadenas idénticas y, a continuación, realiza cuatro llamadas a Equals métodos. La primera llamada al método devuelve truey las tres restantes devuelven 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
open System
open System.Text

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

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

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

Module 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, se llama a la sobrecarga del método fuertemente tipado StringBuilder.Equals(StringBuilder) , que prueba la igualdad de valores. Dado que las cadenas asignadas a los dos StringBuilder objetos son iguales, el método devuelve true. Sin embargo, StringBuilder no invalida Object.Equals(Object). Por este motivo, cuando el StringBuilder objeto se convierte en , Objectcuando se asigna una instancia a una StringBuilder variable de tipo Objecty cuando se pasan dos StringBuilder objetos al Object.Equals(Object, Object) método , se llama al método predeterminadoObject.Equals(Object). Dado StringBuilder que es un tipo de referencia, esto equivale a pasar los dos StringBuilder objetos al ReferenceEquals método . Aunque los tres StringBuilder objetos contienen cadenas idénticas, hacen referencia a tres objetos distintos. Como resultado, estas tres llamadas de método devuelven false.

Puede comparar el objeto actual con otro objeto para obtener igualdad de referencia llamando al ReferenceEquals método . En Visual Basic, también puede usar la is palabra clave (por ejemplo, If Me Is otherObject Then ...).

Notas de los heredadores

Al definir su propio tipo, ese tipo hereda la funcionalidad definida por el Equals método de su tipo base. En la tabla siguiente se muestra la implementación predeterminada del Equals método para las categorías principales de tipos de la .NET Framework.

Categoría de tipo Igualdad definida por Comentarios
Clase derivada directamente de Object Object.Equals(Object) Igualdad de referencia; equivalente a llamar a Object.ReferenceEquals.
Estructura ValueType.Equals Igualdad de valores; comparación directa de bytes por bytes o comparación de campo por campo mediante reflexión.
Enumeración Enum.Equals Los valores deben tener el mismo tipo de enumeración y el mismo valor subyacente.
Delegado MulticastDelegate.Equals Los delegados deben tener el mismo tipo con listas de invocación idénticas.
Interfaz Object.Equals(Object) Igualdad de referencia.

Para un tipo de valor, siempre debe invalidar Equals, porque las pruebas de igualdad que dependen de la reflexión ofrecen un rendimiento deficiente. También puede invalidar la implementación predeterminada de para los tipos de Equals referencia para probar la igualdad de valores en lugar de la igualdad de referencia y definir el significado preciso de la igualdad de valores. Estas implementaciones de Equals devuelven true si los dos objetos tienen el mismo valor, incluso si no son la misma instancia. El implementador del tipo decide qué constituye el valor de un objeto, pero normalmente es algunos o todos los datos almacenados en las variables de instancia del objeto. Por ejemplo, el valor de un String objeto se basa en los caracteres de la cadena; el String.Equals(Object) método invalida el Object.Equals(Object) método para devolver true para dos instancias de cadena que contienen los mismos caracteres en el mismo orden.

En el ejemplo siguiente se muestra cómo invalidar el Object.Equals(Object) método para probar la igualdad de valores. Invalida el Equals método para la Person clase . Si Person acepta su implementación de clase base de igualdad, dos Person objetos solo serían iguales si se hace referencia a un solo objeto. Sin embargo, en este caso, dos Person objetos son iguales si tienen el mismo valor para la Person.Id propiedad .

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
open System

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

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

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

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

Module 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 la IEquatable<T> interfaz para proporcionar una prueba fuertemente tipada para garantizar la igualdad.

Las siguientes instrucciones deben ser verdaderas para todas las implementaciones del Equals(Object) método . En la lista, x, yy z representan referencias de objeto que no son null.

  • x.Equals(x) devuelve true.

  • x.Equals(y) devuelve el mismo valor que y.Equals(x).

  • x.Equals(y) devuelve true si y x y son NaN.

  • Si (x.Equals(y) && y.Equals(z)) devuelve true, x.Equals(z) devuelve true.

  • Las llamadas sucesivas para x.Equals(y) devolver el mismo valor siempre que los objetos a los que x hace referencia y y no se modifiquen.

  • x.Equals(null) devuelve false.

Las implementaciones de Equals no deben producir excepciones; siempre deben devolver un valor. Por ejemplo, si obj es null, el Equals método debe devolver false en lugar de iniciar .ArgumentNullException

Siga estas instrucciones al invalidar Equals(Object):

  • Los tipos que implementan IComparable deben invalidar Equals(Object).

  • Los tipos que invalidan Equals(Object) también deben invalidar GetHashCode; de lo contrario, es posible que las tablas hash no funcionen correctamente.

  • Debe considerar la posibilidad de implementar la IEquatable<T> interfaz para admitir pruebas fuertemente tipadas para la igualdad. La implementación de IEquatable<T>.Equals debe devolver resultados coherentes con Equals.

  • Si el lenguaje de programación admite la sobrecarga del operador y sobrecarga 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. Esto ayuda a garantizar que el código de biblioteca de clases que use Equals (como ArrayList y Hashtable) se comporte de una manera coherente con la forma en que el código de aplicación usa el operador de igualdad.

Directrices para tipos de referencia

Las instrucciones siguientes se aplican a la invalidación Equals(Object) de un tipo de referencia:

  • Considere la posibilidad de invalidar Equals si la semántica del tipo se basa en el hecho de que el tipo representa algunos valores.

  • La mayoría de los tipos de referencia no deben sobrecargar el operador de igualdad, aunque invaliden Equals. Sin embargo, si va a implementar un tipo de referencia destinado a tener semántica de valor, como un tipo de número complejo, debe invalidar el operador de igualdad.

  • No debe invalidar Equals en un tipo de referencia mutable. Esto se debe a que la invalidación Equals requiere que también invalide el GetHashCode método, como se describe en la sección anterior. Esto significa que el código hash de una instancia de un tipo de referencia mutable puede cambiar durante su vigencia, lo que puede hacer que el objeto se pierda en una tabla hash.

Directrices para tipos de valor

Las instrucciones siguientes se aplican a la invalidación Equals(Object) de un tipo de valor:

  • Si va a definir un tipo de valor que incluya uno o varios campos cuyos valores son tipos de referencia, debe invalidar Equals(Object). La Equals(Object) implementación proporcionada por ValueType realiza una comparación de bytes por byte para los 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.

  • Si invalida Equals y el lenguaje de desarrollo admite la sobrecarga del operador, debe sobrecargar el operador de igualdad.

  • Debe implementar la IEquatable<T> interfaz . Llamar al método fuertemente tipado IEquatable<T>.Equals evita la conversión boxing del obj argumento.

Consulte también

Se aplica a

Equals(Object, Object)

Determina si las instancias del objeto especificado se consideran iguales.

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

Parámetros

objA
Object

Primer objeto que se va a comparar.

objB
Object

Segundo objeto que se va a comparar.

Devoluciones

Boolean

Es true si los dos objetos se consideran iguales; en caso contrario, es false. Si tanto objA como objB son null, el método devuelve true.

Ejemplos

En el ejemplo siguiente se muestra el Equals(Object, Object) método y se compara con el ReferenceEquals método .

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
open System

// Class constructor
type Dog(dogBreed) =
    // Public property.
    member _.Breed = dogBreed

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

    override _.GetHashCode() =
        dogBreed.GetHashCode()

    override _.ToString() =
        dogBreed

let m1 = Dog "Alaskan Malamute"
let m2 = Dog "Alaskan Malamute"
let g1 = Dog "Great Pyrenees"
let g2 = g1
let d1 = Dog "Dalmation"
let n1 = Unchecked.defaultof<Dog>
let n2 = Unchecked.defaultof<Dog>

printfn $"null = null: {Object.Equals(n1, n2)}"
printfn $"null Reference Equals null: {Object.ReferenceEquals(n1, n2)}\n"

printfn $"{g1} = {g2}: {Object.Equals(g1, g2)}"
printfn $"{g1} Reference Equals {g2}: {Object.ReferenceEquals(g1, g2)}\n"

printfn $"{m1} = {m2}: {Object.Equals(m1, m2)}"
printfn $"{m1} Reference Equals {m2}: {Object.ReferenceEquals(m1, m2)}\n"

printfn $"{m1} = {d1}: {Object.Equals(m1, d1)}"
printfn $"{m1} Reference Equals {d1}: {Object.ReferenceEquals(m1, d1)}"

// 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

El método estático Equals(Object, Object) indica si dos objetos y objA objB, son iguales. También permite probar objetos cuyo valor es NULL para la igualdad. Compara y objB para la objA igualdad de la siguiente manera:

  • Determina si los dos objetos representan la misma referencia de objeto. Si lo hacen, el método devuelve true. Esta prueba es equivalente a llamar al ReferenceEquals método . Además, si y objA objB son null, el método devuelve true.

  • Determina si o objA objB es null. Si es así, devuelve false.

  • Si los dos objetos no representan la misma referencia de objeto y ninguno es NULL, llama a objA.Equals (objB) y devuelve el resultado. Esto significa que, si objA invalida el Object.Equals(Object) método , se llama a esta invalidación.

Consulte también

Se aplica a