|
Este artículo proviene de un motor de traducción automática. Mueva el puntero sobre las frases del artículo para ver el texto original. Más información.
|
Traducción
Original
|
Object.Equals (Método) (Object)
Espacio de nombres: System
Ensamblado: mscorlib (en mscorlib.dll)
Parámetros
- obj
- Tipo: System.Object
Objeto que se va a comparar con el objeto actual.
Valor devuelto
Tipo: System.Booleanusing 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
Los dos objetos son del mismo tipo. Como se muestra en el ejemplo siguiente, un objeto Byte que tiene un valor de 12 no es un objeto Int32 que tiene un valor de 12, porque los dos objetos tienen distintos tipos en tiempo de ejecución. 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
Los valores de los campos públicos y privados de los dos objetos son iguales. Las pruebas siguientes de ejemplo para la igualdad de valores. Define una estructura Person , que es un tipo de valor, y llama al constructor de clase Person para crear instancias de dos objetos nuevos, person1 y person2de Person , que tienen el mismo valor. Como el resultado del ejemplo, aunque las dos variables de objeto hacen referencia a distintos objetos, person1 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
Notas para los llamadores
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
Notas a herederos.
Object.Equals(Object) | ||
Object.Equals(Object) |
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
x.Equals(x) devuelve true, excepto en los casos que implican tipos de punto flotante. Vea el 60559:2011 de ISO/IEC/IEEE, TI -- Sistemas de microprocesador -- Aritmética flotante. x.Equals(y) devuelve el mismo valor que y.Equals(x). x.Equals(y) devuelve true si x y y son NaN. Si (x.Equals(y) && y.Equals(z)) devuelve true, después x.Equals(z) devuelve true. Las llamadas sucesivas a x.Equals(y) devuelven el mismo valor siempre que los objetos a los que hace referencia x y y no se modifiquen. x.Equals(null) devuelve false.
Los tipos que implementan IComparable deben reemplazar el método Equals(Object). Los tipos que reemplazan Equals(Object) también deben reemplazar GetHashCode; si no, las tablas hash podrían no funcionar correctamente. Si el lenguaje de programación admite la sobrecarga de operadores y se sobrecarga el operador de igualdad para un tipo determinado, también debe reemplazar el método Equals(Object) devuelva el mismo resultado que el operador de igualdad. Esto ayuda a garantizar que el código de biblioteca de clases que utilice Equals (como ArrayList y Hashtable) se comporta de forma coherente con la manera en que el código de aplicación usa el operador de igualdad.
Instrucciones para los tipos de referencia
Considere reemplazar Equals si la semántica de tipos 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 reemplacen el método Equals. No obstante, cuando se implemente un tipo de referencia destinado a tener semántica de valor, como un tipo de número complejo, debe reemplazarse el operador de igualdad.
Instrucciones para los tipos de valor
Si define un tipo de valor que incluya uno o más campos cuyos valores son tipos de referencia, debe invalidar Equals(Object). La implementación Equals(Object) proporcionada por ValueType realiza una comparación de byte-por- bytes para los tipos de valor cuyos campos son todos los tipos de valor, pero utiliza la reflexión para realizar una comparación de campo-por- campo de los tipos de valor cuyos campos incluyen los tipos de referencia. Si reemplaza Equals y el lenguaje de desarrollo admite la sobrecarga de operadores, debe sobrecargar el operador de igualdad.
using System; class Point { protected int x, y; public Point() { this.x = 0; this.y = 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() != obj.GetType()) { return false; } else { Point p = (Point) obj; return (x == p.x) && (y == p.y); } } public override int GetHashCode() { return x ^ y; } } class Point3D: Point { int z; public Point3D(int X, int Y, int Z) { this.x = X; this.y = Y; this.z = Z; } public override bool Equals(Object obj) { return base.Equals(obj) && z == ((Point3D)obj).z; } public override int GetHashCode() { return base.GetHashCode() ^ 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); if (!point2D.Equals(point3Da)) { Console.WriteLine("point2D does not equal point3Da"); } if (!point3Db.Equals(point2D)) { Console.WriteLine("point3Db does not equal point2D"); } if (point3Da.Equals(point3Db)) { Console.WriteLine("point3Da equals point3Db"); } } } // The example displays the following output: // point2D does not equal point3Da // point3Db does not equal point2D // point3Da equals point3Db
using System; class Rectangle { 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) { // Performs an equality check on two rectangles (Point object pairs). if (obj == null || GetType() != obj.GetType()) return false; Rectangle r = (Rectangle)obj; //Uses Equals to compare variables. return a.Equals(r.a) && b.Equals(r.b); } public override int GetHashCode() { return a.GetHashCode() ^ b.GetHashCode(); } } class Point { private int x; private 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 x.GetHashCode() ^ 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); if (r1.Equals(r2)) { Console.WriteLine("Rectangle r1 equals rectangle r2!"); } if (!r2.Equals(r3)) { Console.WriteLine("But rectangle r2 does not equal rectangle r3."); } } } // The example displays the following output: // Rectangle r1 equals rectangle r2! // But rectangle r2 does not equal rectangle r3.
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 re.GetHashCode() ^ 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); } } 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; if (cmplx1 != cmplx2) Console.WriteLine("The two objects are not equal."); if (! cmplx1.Equals(cmplx2)) Console.WriteLine("The two objects are not equal."); cmplx2.re = 4.0; if (cmplx1 == cmplx2) Console.WriteLine("The two objects are now equal!"); if (cmplx1.Equals(cmplx2)) Console.WriteLine("The two objects are now equal!"); } } // The example displays the following output: // The two objects are not equal. // The two objects are not equal. // The two objects are now equal! // The two objects are now equal!
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (no se admite el rol Server Core), Windows Server 2008 R2 (se admite el rol Server Core con SP1 o versiones posteriores; no se admite Itanium)
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
