Equals Método (Object)
Collapse the table of content
Expand the table of content
Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Object.Equals (Método) (Object)

 

Determina si el objeto especificado es igual al objeto actual.

Espacio de nombres:   System
Ensamblado:  mscorlib (en mscorlib.dll)

public virtual bool Equals(
	object obj
)

Parámetros

obj
Type: System.Object

Objeto que se va a comparar con el objeto actual.

Valor devuelto

Type: System.Boolean

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

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.

  • If the current instance is a reference type, the M:System.Object.Equals(System.Object) method tests for reference equality, and a call to the M:System.Object.Equals(System.Object) method is equivalent to a call to the M:System.Object.ReferenceEquals(System.Object,System.Object) method. Reference equality means that the object variables that are compared refer to the same object. The following example illustrates the result of such a comparison. 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. It also assigns person1a to another object variable, person1b. As the output from the example shows, person1a and person1b are equal because they reference the same object. 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
    
  • If the current instance is a value type, the M:System.Object.Equals(System.Object) method tests for value equality. Value equality means the following:

    • The two objects are of the same type. As the following example shows, a T:System.Byte object that has a value of 12 does not equal an T:System.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
      
    • The values of the public and private fields of the two objects are equal. The following example tests for value equality. 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. 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
      

Because the T:System.Object class is the base class for all types in the .NET Framework, the M:System.Object.Equals(System.Object) method provides the default equality comparison for all other types. However, types often override the M:System.Object.Equals(System.Object) method to implement value equality. For more information, see the Notes for Callers and Notes for Inheritors sections.

When you call the M:System.Object.Equals(System.Object) method overload on a class in the wrt, it provides the default behavior for classes that don’t override M:System.Object.Equals(System.Object). This is part of the support that the .NET Framework provides for the wrt (see .NET Framework Support for Windows Store Apps and Windows Runtime). Classes in the wrt don’t inherit T:System.Object, and currently don’t implement an M:System.Object.Equals(System.Object)method. However, they appear to have M:System.Object.ToString, M:System.Object.Equals(System.Object), and M:System.Object.GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods.

System_CAPS_noteNota

Windows en tiempo de ejecución classes that are written in C# or Visual Basic can override the Equals(Object) method overload.

Derived classes frequently override the M:System.Object.Equals(System.Object) method to implement value equality. In addition, types also frequently provide an additional strongly typed overload to the Equals method, typically by implementing the T:System.IEquatable`1 interface. When you call the Equals method to test for equality, you should know whether the current instance overrides M:System.Object.Equals(System.Object) and understand how a particular call to an Equals method is resolved. Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value.

The following example provides an illustration. It instantiates three T:System.Text.StringBuilder objects with identical strings, and then makes four calls to Equals methods. 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

In the first case, the strongly typed M:System.Text.StringBuilder.Equals(System.Text.StringBuilder) method overload, which tests for value equality, is called. Because the strings assigned to the two T:System.Text.StringBuilder objects are equal, the method returns true. However, T:System.Text.StringBuilder does not override M:System.Object.Equals(System.Object). Because of this, when the T:System.Text.StringBuilder object is cast to an T:System.Object, when a T:System.Text.StringBuilder instance is assigned to a variable of type T:System.Object, and when the M:System.Object.Equals(System.Object,System.Object) method is passed two T:System.Text.StringBuilder objects, the default M:System.Object.Equals(System.Object) method is called. Because T:System.Text.StringBuilder is a reference type, this is equivalent to passing the two T:System.Text.StringBuilder objects to the M:System.Object.ReferenceEquals(System.Object,System.Object) method. Although all three T:System.Text.StringBuilder objects contain identical strings, they refer to three distinct objects. As a result, these three method calls return false.

You can compare the current object to another object for reference equality by calling the M:System.Object.ReferenceEquals(System.Object,System.Object) method. In Visual Basic, you can also use the is keyword (for example, If Me Is otherObject Then ...).

When you define your own type, that type inherits the functionality defined by the Equals method of its base type. The following table lists the default implementation of the Equals method for the major categories of types in the .NET Framework.

Type category

Equality defined by

Comments

Class derived directly from T:System.Object

Object.Equals(Object)

Reference equality; equivalent to calling M:System.Object.ReferenceEquals(System.Object,System.Object).

Structure

ValueType.Equals

Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection.

Enumeration

Enum.Equals

Values must have the same enumeration type and the same underlying value.

Delegate

MulticastDelegate.Equals

Delegates must have the same type with identical invocation lists.

Interface

Object.Equals(Object)

Reference equality.

For a value type, you should always override M:System.Object.Equals(System.Object), because tests for equality that rely on reflection offer poor performance. You can also override the default implementation of M:System.Object.Equals(System.Object) for reference types to test for value equality instead of reference equality and to define the precise meaning of value equality. Such implementations of M:System.Object.Equals(System.Object) return true if the two objects have the same value, even if they are not the same instance. The type's implementer decides what constitutes an object's value, but it is typically some or all the data stored in the instance variables of the object. For example, the value of a T:System.String object is based on the characters of the string; the M:System.String.Equals(System.Object) method overrides the M:System.Object.Equals(System.Object) method to return true for any two string instances that contain the same characters in the same order.

The following example shows how to override the M:System.Object.Equals(System.Object) method to test for value equality. It overrides the M:System.Object.Equals(System.Object) method for the Person class. If Person accepted its base class implementation of equality, two Person objects would be equal only if they referenced a single object. 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

In addition to overriding M:System.Object.Equals(System.Object), you can implement the T:System.IEquatable`1 interface to provide a strongly typed test for equality.

The following statements must be true for all implementations of the M:System.Object.Equals(System.Object) method. In the list, x, y, and z represent object references that are not null.

  • x.Equals(x) returns true, except in cases that involve floating-point types. See ISO/IEC/IEEE 60559:2011, Information technology -- Microprocessor Systems -- Floating-Point arithmetic.

  • x.Equals(y) returns the same value as y.Equals(x).

  • x.Equals(y) returns true if both x and y are NaN.

  • If (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.

  • 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) returns false.

Implementations of M:System.Object.Equals(System.Object) must not throw exceptions; they should always return a value. For example, if obj is null, the M:System.Object.Equals(System.Object) method should return false instead of throwing an T:System.ArgumentNullException.

Follow these guidelines when overriding M:System.Object.Equals(System.Object):

  • Types that implement T:System.IComparable must override M:System.Object.Equals(System.Object).

  • Types that override M:System.Object.Equals(System.Object) must also override M:System.Object.GetHashCode; otherwise, hash tables might not work correctly.

  • You should consider implementing the T:System.IEquatable`1 interface to support strongly typed tests for equality. Your M:System.IEquatable`1.Equals(`0) implementation should return results that are consistent with M:System.Object.Equals(System.Object).

  • If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override the M:System.Object.Equals(System.Object) method to return the same result as the equality operator. This helps ensure that class library code that uses M:System.Object.Equals(System.Object) (such as T:System.Collections.ArrayList and T:System.Collections.Hashtable) behaves in a manner that is consistent with the way the equality operator is used by application code.

The following guidelines apply to overriding M:System.Object.Equals(System.Object) for a reference type:

  • Consider overriding M:System.Object.Equals(System.Object) if the semantics of the type are based on the fact that the type represents some value(s).

  • Most reference types must not overload the equality operator, even if they override M:System.Object.Equals(System.Object). 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.

  • You should not override M:System.Object.Equals(System.Object) on a mutable reference type. This is because overriding M:System.Object.Equals(System.Object) requires that you also override the M:System.Object.GetHashCode method, as discussed in the previous section. This means that the hash code of an instance of a mutable reference type can change during its lifetime, which can cause the object to be lost in a hash table.

The following guidelines apply to overriding M:System.Object.Equals(System.Object) for a value type:

  • If you are defining a value type that includes one or more fields whose values are reference types, you should override M:System.Object.Equals(System.Object). The M:System.Object.Equals(System.Object) implementation provided by T:System.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.

  • If you override M:System.Object.Equals(System.Object) and your development language supports operator overloading, you must overload the equality operator.

  • You should implement the T:System.IEquatable`1 interface. Calling the strongly typed M:System.IEquatable`1.Equals(`0) method avoids boxing the obj argument.

The following example shows a Point class that overrides the M:System.Object.Equals(System.Object) method to provide value equality, and a Point3D class that is derived from Point. Because Point overrides M:System.Object.Equals(System.Object) to test for value equality, the M:System.Object.Equals(System.Object) method is not called. However, Point3D.Equals calls Point.Equals because Point implements M:System.Object.Equals(System.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

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. If either check fails, the method returns false.

The Point.Equals method calls the M:System.Object.GetType method to determine whether the run-time types of the two objects are identical. 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. 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.

In Point3D.Equals, the inherited Point.Equals method, which overrides M:System.Object.Equals(System.Object), is invoked before anything else is done. 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. If it is a Point3D object, it is cast to a Point object and passed to the base class implementation of M:System.Object.Equals(System.Object). Only when the inherited Point.Equals method returns true does the method compare the z instance fields introduced in the derived class.

The following example defines a Rectangle class that internally implements a rectangle as two Point objects. The Rectangle class also overrides M:System.Object.Equals(System.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

Some languages such as C# and Visual Basic support operator overloading. When a type overloads the equality operator, it must also override the M:System.Object.Equals(System.Object) method to provide the same functionality. This is typically accomplished by writing the M:System.Object.Equals(System.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

Because Complex is a value type, it cannot be derived from. Therefore, the override to M:System.Object.Equals(System.Object) method need not call M:System.Object.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.

Universal Windows Platform
Disponible desde 4.5
.NET Framework
Disponible desde 1.1
Portable Class Library
Compatible con: portable .NET platforms
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1
Volver al principio
Mostrar:
© 2016 Microsoft