Exportar (0) Imprimir
Expandir Tudo
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original
Este tópico ainda não foi avaliado como - Avalie este tópico

Object.Equals Método (Object)

Determina se o Object especificado é igual ao Object atual.

Namespace:  System
Assembly:  mscorlib (em mscorlib. dll)
public virtual bool Equals(
	Object obj
)

Parâmetros

obj
Tipo: System.Object
The Object to compare with the current Object.

Valor de retorno

Tipo: System.Boolean
true if the specified Object is equal to the current Object; otherwise, false.

The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types.Referência igualdade significa que as referências de objeto que são comparadas se referir ao mesmo objeto.Bitwise means the Objects that are compared have the same Binário representation.

Note that a derived type might override the Equals method to implement value equality.Igualdade value means the Objects compared have the same valor even though they have different Binário representations.For example, consider two Decimal objects that represent the numbers 1.10 and 1.1000.The Decimal objects do not have bitwise equality because they have different binary representations to account for the different number of trailing zeroes.No entanto, os objetos têm valor igualdade porque os números 1.10 e 1.1000 são considerados iguais para fins de comparação como os zeros à direita são.

OBSERVAÇÕES PARA Implementers:

Esse método pode ser substituído por uma classe derivada.For example, many of the base data types return true if both objects represent the same value; otherwise, false.

Este método somente compara primitivos e objetos.Ele deve ser substituído para comparar estruturas mais complexas, como matrizes de objetos.

The following statements must be true for all implementations of the Equals 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 60559:1989 IEC, Binário Arithmetic Floating-point for Systems Microprocessor.

  • x.igual a(y) returns the same valor as y.igual a(x).

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

  • (x.Equals(y) && y.Equals(z)) returns true if and only if x.Equals(z) returns true.

  • Successive Calls to x.igual a(y) return the same valor as long as the Objects relacionado by x and y are not modified.

  • x.Equals(null) returns false.

See GetHashCode for additional required behaviors pertaining to the Equals method.

Implementations of Equals must not throw exceptions.

For some kinds of objects, it is desirable to have Equals test for value equality instead of referential equality.Such implementations of Equals return true if the two objects have the same "value", even if they are not the same instance.Implementador the tipo 's decides What constitutes an Objeto's "valor", But it is geralmente some or All the dados stored in the variables instância of the Objeto.For example, the value of a String is based on the characters of the string; the Equals method of the String class returns true for any two string instances that contain exactly the same characters in the same order.

Types that implement IComparable must override Equals.

Types that override Equals must also override GetHashCode; otherwise, Hashtable might not work correctly.

If your programming language supports operator overloading and if you choose to overload the equality operator for a given type, that type must override the Equals method.Such implementations of the Equals method must return the same results as the equality operator.Following this guideline will help ensure that class library code using Equals (such as ArrayList and Hashtable) behaves in a manner that is consistent with the way the equality operator is used by application code.

As diretrizes a seguir são para implementar um tipo de valor:

  • Consider overriding Equals to gain increased performance over that provided by the default implementation of Equals on ValueType.

  • If you override Equals and the language supports operator overloading, you must overload the equality operator for your value type.

As diretrizes a seguir são para implementar um tipo de referência:

  • Consider overriding Equals on a reference type 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 Equals.No entanto, se você estiver implementando um tipo de referência que pretende ter semântica valor, como um tipo número complexo, você deve substituir o operador de igualdade.

O exemplo de código a seguir compara a instância atual com outro objeto.

using System;

public class Sample {
    void Method() {
    Object Obj1 = new Object();
    Object Obj2 = new Object();
    Console.WriteLine(Obj1.Equals(Obj2)); //===> false
    Obj2 = Obj1;
    Console.WriteLine(Obj1.Equals(Obj2)); //===> true
    }
}


import System.*;

public class Sample
{
    void Method()
    {
        Object obj1 = new Object();
        Object obj2 = new Object();
        Console.WriteLine(obj1.Equals(obj2)); //===> false
        obj2 = obj1;
        Console.WriteLine(obj1.Equals(obj2)); //===> true
    } //Method
} //Sample


The following example shows a Point class that overrides the Equals method to provide value equality and a class Point3D, which is derived from Point.Because Point 's override of Equals is the first in the inheritance chain to introduce value equality, the Equals method of the base class (which is inherited from Object and checks for referential equality) is not invoked.However, Point3D.Equals invokes Point.Equals because Point implements Equals in a manner that provides value equality.

using System;

class Point: Object {
   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 || GetType() != obj.GetType()) return false;
      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 MyClass {

  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("Likewise, point3Db does not equal point2D.");
     }
     if (point3Da.Equals(point3Db)) {
        Console.WriteLine("However, point3Da equals point3Db.");
     }

  } 
}
// ----------------------------------
// Output should be:
// 
// point2D does not equal point3Da.
// Likewise, point3Db does not equal point2D.
// However, point3Da equals point3Db.


The Point.Equals method checks that the obj argument is not null and that it references an instance of the same type as this object.If either of those checks fail, the method returns false.

The Equals method uses GetType to determine whether the run-time types of the two objects are identical.(Note that typeof is not used here because it returns the static type.) If the method used a check of the form obj is Point, 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 runtime 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 variables of the two objects.

In Point3D.Equals, the inherited Equals method is invoked before anything else is done; the inherited Equals method checks to see that obj is not null, that obj is an instance of the same class as this object and that the inherited instance variables match.Only when the inherited Equals returns true does the method compare the instance variables introduced in the derived class.Specifically, the cast to Point3D is not executed unless obj has been determined to be of type Point3D or a derived class of Point3D.

In the previous example, operator == (the equality operator) is used to compare the individual instance variables.In some cases, it is appropriate to use the Equals method to compare instance variables in an Equals implementation, as shown in the following code example.

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 added for clean compile
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 MyClass {
   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.");
      }
   }
}
// ------------------------------
// Output should be:
// Rectangle r1 equals rectangle r2!
// But rectangle r2 does not equal rectangle r3.


Em alguns idiomas, como C#, Operador sobrecarga é suportado.When a type overloads operator ==, it must also override the Equals method to provide the same functionality.This is typically accomplished by writing the Equals method in terms of the overloaded operator ==, as in the following code 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 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.");
    }

    cmplx2.re = 4.0;

    if (cmplx1 == cmplx2) {
      Console.WriteLine("The two objects are now equal!");
    }
  }
}
// ---------------------------------
// Output should be:
//
// The two objects are not equal.
// The two objects are now equal!


Because Complex is a C# struct (a value type), it cannot be derived from; therefore, the Equals method need not compare the GetType results for each object, but can instead use the is operator to check the type of the obj parameter.

Isso foi útil para você?
(1500 caracteres restantes)
Agradecemos os seus comentários

Contribuições da comunidade

ADICIONAR
Mostrar:
© 2014 Microsoft. Todos os direitos reservados.