Object.Equals Método
Definição
Determina se duas instâncias de objeto são iguais.Determines whether two object instances are equal.
Sobrecargas
Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. |
Equals(Object, Object) |
Determina se as instâncias de objeto especificadas são consideradas iguais.Determines whether the specified object instances are considered equal. |
Equals(Object)
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.
public:
virtual bool Equals(System::Object ^ obj);
public virtual bool Equals (object obj);
abstract member Equals : obj -> bool
override this.Equals : obj -> bool
Public Overridable Function Equals (obj As Object) As Boolean
Parâmetros
- obj
- Object
O objeto para comparar com o objeto atual.The object to compare with the current object.
Retornos
true
se o objeto especificado for igual ao objeto atual; caso contrário, false
.true
if the specified object is equal to the current object; otherwise, false
.
Exemplos
O exemplo a seguir mostra uma classe Point
que substitui o método Equals para fornecer igualdade de valor e uma classe Point3D
que é derivada de Point
.The following example shows a Point
class that overrides the Equals method to provide value equality, and a Point3D
class that is derived from Point
. Como Point
substitui Object.Equals(Object) para testar a igualdade de valor, o método Object.Equals(Object) não é chamado.Because Point
overrides Object.Equals(Object) to test for value equality, the Object.Equals(Object) method is not called. No entanto, Point3D.Equals
chama Point.Equals
porque Point
implementa Object.Equals(Object) de uma maneira que fornece igualdade de valor.However, Point3D.Equals
calls Point.Equals
because Point
implements Object.Equals(Object) in a manner that provides value equality.
using System;
class Point
{
protected int x, y;
public Point() : this(0, 0)
{ }
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override bool Equals(Object obj)
{
//Check for null and compare run-time types.
if ((obj == null) || ! this.GetType().Equals(obj.GetType()))
{
return false;
}
else {
Point p = (Point) obj;
return (x == p.x) && (y == p.y);
}
}
public override int GetHashCode()
{
return (x << 2) ^ y;
}
public override string ToString()
{
return String.Format("Point({0}, {1})", x, y);
}
}
sealed class Point3D: Point
{
int z;
public Point3D(int x, int y, int z) : base(x, y)
{
this.z = z;
}
public override bool Equals(Object obj)
{
Point3D pt3 = obj as Point3D;
if (pt3 == null)
return false;
else
return base.Equals((Point)obj) && z == pt3.z;
}
public override int GetHashCode()
{
return (base.GetHashCode() << 2) ^ z;
}
public override String ToString()
{
return String.Format("Point({0}, {1}, {2})", x, y, z);
}
}
class Example
{
public static void Main()
{
Point point2D = new Point(5, 5);
Point3D point3Da = new Point3D(5, 5, 2);
Point3D point3Db = new Point3D(5, 5, 2);
Point3D point3Dc = new Point3D(5, 5, -1);
Console.WriteLine("{0} = {1}: {2}",
point2D, point3Da, point2D.Equals(point3Da));
Console.WriteLine("{0} = {1}: {2}",
point2D, point3Db, point2D.Equals(point3Db));
Console.WriteLine("{0} = {1}: {2}",
point3Da, point3Db, point3Da.Equals(point3Db));
Console.WriteLine("{0} = {1}: {2}",
point3Da, point3Dc, point3Da.Equals(point3Dc));
}
}
// The example displays the following output:
// Point(5, 5) = Point(5, 5, 2): False
// Point(5, 5) = Point(5, 5, 2): False
// Point(5, 5, 2) = Point(5, 5, 2): True
// Point(5, 5, 2) = Point(5, 5, -1): False
Class Point
Protected x, y As Integer
Public Sub New()
Me.x = 0
Me.y = 0
End Sub
Public Sub New(x As Integer, y As Integer)
Me.x = x
Me.y = y
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
' Check for null and compare run-time types.
If obj Is Nothing OrElse Not Me.GetType().Equals(obj.GetType()) Then
Return False
Else
Dim p As Point = DirectCast(obj, Point)
Return x = p.x AndAlso y = p.y
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return (x << 2) XOr y
End Function
Public Overrides Function ToString() As String
Return String.Format("Point({0}, {1})", x, y)
End Function
End Class
Class Point3D : Inherits Point
Private z As Integer
Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer)
MyBase.New(x, y)
Me.z = Z
End Sub
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Dim pt3 As Point3D = TryCast(obj, Point3D)
If pt3 Is Nothing Then
Return False
Else
Return MyBase.Equals(CType(pt3, Point)) AndAlso z = pt3.Z
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return (MyBase.GetHashCode() << 2) XOr z
End Function
Public Overrides Function ToString() As String
Return String.Format("Point({0}, {1}, {2})", x, y, z)
End Function
End Class
Module Example
Public Sub Main()
Dim point2D As New Point(5, 5)
Dim point3Da As New Point3D(5, 5, 2)
Dim point3Db As New Point3D(5, 5, 2)
Dim point3Dc As New Point3D(5, 5, -1)
Console.WriteLine("{0} = {1}: {2}",
point2D, point3Da, point2D.Equals(point3Da))
Console.WriteLine("{0} = {1}: {2}",
point2D, point3Db, point2D.Equals(point3Db))
Console.WriteLine("{0} = {1}: {2}",
point3Da, point3Db, point3Da.Equals(point3Db))
Console.WriteLine("{0} = {1}: {2}",
point3Da, point3Dc, point3Da.Equals(point3Dc))
End Sub
End Module
' The example displays the following output
' Point(5, 5) = Point(5, 5, 2): False
' Point(5, 5) = Point(5, 5, 2): False
' Point(5, 5, 2) = Point(5, 5, 2): True
' Point(5, 5, 2) = Point(5, 5, -1): False
O método Point.Equals
verifica se o argumento obj
não é nulo e se faz referência a uma instância do mesmo tipo que esse objeto.The Point.Equals
method checks to make sure that the obj
argument is not null and that it references an instance of the same type as this object. Se qualquer verificação falhar, o método retornará false
.If either check fails, the method returns false
.
O método Point.Equals
chama o método GetType para determinar se os tipos de tempo de execução dos dois objetos são idênticos.The Point.Equals
method calls the GetType method to determine whether the run-time types of the two objects are identical. Se o método usou uma verificação do formulário obj is Point
em C# ou TryCast(obj, Point)
no Visual Basic, a verificação retornará true
em casos em que obj
é uma instância de uma classe derivada de Point
, embora obj
e a instância atual não sejam do mesmo tipo de tempo de execução.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. Depois de verificar que ambos os objetos são do mesmo tipo, o método converte obj
para o tipo Point
e retorna o resultado da comparação dos campos de instância dos dois objetos.Having verified that both objects are of the same type, the method casts obj
to type Point
and returns the result of comparing the instance fields of the two objects.
No Point3D.Equals
, o método herdado Point.Equals
, que substitui Object.Equals(Object), é invocado antes de qualquer outra coisa ser feita.In Point3D.Equals
, the inherited Point.Equals
method, which overrides Object.Equals(Object), is invoked before anything else is done. Como Point3D
é uma classe selada (NotInheritable
no Visual Basic), uma verificação no formulário obj is Point
C# ou TryCast(obj, Point)
em Visual Basic é adequada para garantir que obj
seja um objeto Point3D
.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. Se for um objeto Point3D
, ele será convertido em um objeto Point
e passado para a implementação da classe base de Equals.If it is a Point3D
object, it is cast to a Point
object and passed to the base class implementation of Equals. Somente quando o método herdado Point.Equals
retorna true
faz o método comparar os campos de instância de z
introduzidos na classe derivada.Only when the inherited Point.Equals
method returns true
does the method compare the z
instance fields introduced in the derived class.
O exemplo a seguir define uma classe Rectangle
que implementa internamente um retângulo como dois objetos Point
.The following example defines a Rectangle
class that internally implements a rectangle as two Point
objects. A classe Rectangle
também substitui Object.Equals(Object) para fornecer igualdade de valor.The Rectangle
class also overrides Object.Equals(Object) to provide for value equality.
using System;
class Rectangle
{
private Point a, b;
public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY)
{
this.a = new Point(upLeftX, upLeftY);
this.b = new Point(downRightX, downRightY);
}
public override bool Equals(Object obj)
{
// Perform an equality check on two rectangles (Point object pairs).
if (obj == null || GetType() != obj.GetType())
return false;
Rectangle r = (Rectangle)obj;
return a.Equals(r.a) && b.Equals(r.b);
}
public override int GetHashCode()
{
return Tuple.Create(a, b).GetHashCode();
}
public override String ToString()
{
return String.Format("Rectangle({0}, {1}, {2}, {3})",
a.x, a.y, b.x, b.y);
}
}
class Point
{
internal int x;
internal int y;
public Point(int X, int Y)
{
this.x = X;
this.y = Y;
}
public override bool Equals (Object obj)
{
// Performs an equality check on two points (integer pairs).
if (obj == null || GetType() != obj.GetType()) return false;
Point p = (Point)obj;
return (x == p.x) && (y == p.y);
}
public override int GetHashCode()
{
return Tuple.Create(x, y).GetHashCode();
}
}
class Example
{
public static void Main()
{
Rectangle r1 = new Rectangle(0, 0, 100, 200);
Rectangle r2 = new Rectangle(0, 0, 100, 200);
Rectangle r3 = new Rectangle(0, 0, 150, 200);
Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2));
Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3));
Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3));
}
}
// The example displays the following output:
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
Class Rectangle
Private a, b As Point
Public Sub New(ByVal upLeftX As Integer, ByVal upLeftY As Integer, _
ByVal downRightX As Integer, ByVal downRightY As Integer)
Me.a = New Point(upLeftX, upLeftY)
Me.b = New Point(downRightX, downRightY)
End Sub
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
' Performs an equality check on two rectangles (Point object pairs).
If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
Return False
End If
Dim r As Rectangle = CType(obj, Rectangle)
Return a.Equals(r.a) AndAlso b.Equals(r.b)
End Function
Public Overrides Function GetHashCode() As Integer
Return Tuple.Create(a, b).GetHashCode()
End Function
Public Overrides Function ToString() As String
Return String.Format("Rectangle({0}, {1}, {2}, {3})",
a.x, a.y, b.x, b.y)
End Function
End Class
Class Point
Friend x As Integer
Friend y As Integer
Public Sub New(ByVal X As Integer, ByVal Y As Integer)
Me.x = X
Me.y = Y
End Sub
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
' Performs an equality check on two points (integer pairs).
If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
Return False
Else
Dim p As Point = CType(obj, Point)
Return x = p.x AndAlso y = p.y
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return Tuple.Create(x, y).GetHashCode()
End Function
End Class
Class Example
Public Shared Sub Main()
Dim r1 As New Rectangle(0, 0, 100, 200)
Dim r2 As New Rectangle(0, 0, 100, 200)
Dim r3 As New Rectangle(0, 0, 150, 200)
Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2))
Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3))
Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3))
End Sub
End Class
' The example displays the following output:
' Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
' Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
' Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
Alguns idiomas, como C# e Visual Basic o sobrecarregamento de operadores de suporte.Some languages such as C# and Visual Basic support operator overloading. Quando um tipo sobrecarrega o operador de igualdade, ele também deve substituir o método Equals(Object) para fornecer a mesma funcionalidade.When a type overloads the equality operator, it must also override the Equals(Object) method to provide the same functionality. Normalmente, isso é feito escrevendo o método Equals(Object) em termos do operador de igualdade sobrecarregado, como no exemplo a seguir.This is typically accomplished by writing the Equals(Object) method in terms of the overloaded equality operator, as in the following example.
using System;
public struct Complex
{
public double re, im;
public override bool Equals(Object obj)
{
return obj is Complex && this == (Complex)obj;
}
public override int GetHashCode()
{
return Tuple.Create(re, im).GetHashCode();
}
public static bool operator ==(Complex x, Complex y)
{
return x.re == y.re && x.im == y.im;
}
public static bool operator !=(Complex x, Complex y)
{
return !(x == y);
}
public override String ToString()
{
return String.Format("({0}, {1})", re, im);
}
}
class MyClass
{
public static void Main()
{
Complex cmplx1, cmplx2;
cmplx1.re = 4.0;
cmplx1.im = 1.0;
cmplx2.re = 2.0;
cmplx2.im = 1.0;
Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 != cmplx2);
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2));
cmplx2.re = 4.0;
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 == cmplx2);
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2));
}
}
// The example displays the following output:
// (4, 1) <> (2, 1): True
// (4, 1) = (2, 1): False
// (4, 1) = (4, 1): True
// (4, 1) = (4, 1): True
Public Structure Complex
Public re, im As Double
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
Return TypeOf obj Is Complex AndAlso Me = CType(obj, Complex)
End Function
Public Overrides Function GetHashCode() As Integer
Return Tuple.Create(re, im).GetHashCode()
End Function
Public Shared Operator = (x As Complex, y As Complex) As Boolean
Return x.re = y.re AndAlso x.im = y.im
End Operator
Public Shared Operator <> (x As Complex, y As Complex) As Boolean
Return Not (x = y)
End Operator
Public Overrides Function ToString() As String
Return String.Format("({0}, {1})", re, im)
End Function
End Structure
Class Example
Public Shared Sub Main()
Dim cmplx1, cmplx2 As Complex
cmplx1.re = 4.0
cmplx1.im = 1.0
cmplx2.re = 2.0
cmplx2.im = 1.0
Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 <> cmplx2)
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))
cmplx2.re = 4.0
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 = cmplx2)
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))
End Sub
End Class
' The example displays the following output:
' (4, 1) <> (2, 1): True
' (4, 1) = (2, 1): False
' (4, 1) = (4, 1): True
' (4, 1) = (4, 1): True
Como Complex
é um tipo de valor, não pode ser derivado de.Because Complex
is a value type, it cannot be derived from. Portanto, a substituição para Equals(Object) método não precisa chamar GetType para determinar o tipo de tempo de execução preciso de cada objeto, mas, em vez disso, pode C# usar o operador is
no ou o operador TypeOf
no Visual Basic para verificar o tipo do parâmetro obj
.Therefore, the override to Equals(Object) method need not call GetType to determine the precise run-time type of each object, but can instead use the is
operator in C# or the TypeOf
operator in Visual Basic to check the type of the obj
parameter.
Comentários
O tipo de comparação entre a instância atual e o parâmetro obj
depende se a instância atual é um tipo de referência ou um tipo de valor.The type of comparison between the current instance and the obj
parameter depends on whether the current instance is a reference type or a value type.
Se a instância atual for um tipo de referência, o método Equals(Object) testará a igualdade de referência e uma chamada para o método Equals(Object) é equivalente a uma chamada para o método ReferenceEquals.If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Igualdade de referência significa que as variáveis de objeto comparadas referem-se ao mesmo objeto.Reference equality means that the object variables that are compared refer to the same object. O exemplo a seguir ilustra o resultado de tal comparação.The following example illustrates the result of such a comparison. Ele define uma classe
Person
, que é um tipo de referência, e chama o construtor da classePerson
para instanciar dois novos objetosPerson
,person1a
eperson2
, que têm o mesmo valor.It defines aPerson
class, which is a reference type, and calls thePerson
class constructor to instantiate two newPerson
objects,person1a
andperson2
, which have the same value. Ele também atribuiperson1a
a outra variável de objeto,person1b
.It also assignsperson1a
to another object variable,person1b
. Como a saída do exemplo mostra,person1a
eperson1b
são iguais porque fazem referência ao mesmo objeto.As the output from the example shows,person1a
andperson1b
are equal because they reference the same object. No entanto,person1a
eperson2
não são iguais, embora tenham o mesmo valor.However,person1a
andperson2
are not equal, although they have the same value.using System; // Define a reference type that does not override Equals. public class Person { private string personName; public Person(string name) { this.personName = name; } public override string ToString() { return this.personName; } } public class Example { public static void Main() { Person person1a = new Person("John"); Person person1b = person1a; Person person2 = new Person(person1a.ToString()); Console.WriteLine("Calling Equals:"); Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b)); Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2)); Console.WriteLine("\nCasting to an Object and calling Equals:"); Console.WriteLine("person1a and person1b: {0}", ((object) person1a).Equals((object) person1b)); Console.WriteLine("person1a and person2: {0}", ((object) person1a).Equals((object) person2)); } } // The example displays the following output: // person1a and person1b: True // person1a and person2: False // // Casting to an Object and calling Equals: // person1a and person1b: True // person1a and person2: False
' Define a reference type that does not override Equals. Public Class Person Private personName As String Public Sub New(name As String) Me.personName = name End Sub Public Overrides Function ToString() As String Return Me.personName End Function End Class Module Example Public Sub Main() Dim person1a As New Person("John") Dim person1b As Person = person1a Dim person2 As New Person(person1a.ToString()) Console.WriteLine("Calling Equals:") Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b)) Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2)) Console.WriteLine() Console.WriteLine("Casting to an Object and calling Equals:") Console.WriteLine("person1a and person1b: {0}", CObj(person1a).Equals(CObj(person1b))) Console.WriteLine("person1a and person2: {0}", CObj(person1a).Equals(CObj(person2))) End Sub End Module ' The example displays the following output: ' Calling Equals: ' person1a and person1b: True ' person1a and person2: False ' ' Casting to an Object and calling Equals: ' person1a and person1b: True ' person1a and person2: False
Se a instância atual for um tipo de valor, o método de Equals(Object) testará para igualdade de valor.If the current instance is a value type, the Equals(Object) method tests for value equality. Igualdade de valor significa o seguinte:Value equality means the following:
Os dois objetos são do mesmo tipo.The two objects are of the same type. Como mostra o exemplo a seguir, um objeto Byte que tem um valor de 12 não é igual a um objeto Int32 que tem um valor de 12, porque os dois objetos têm diferentes tipos de tempo de execução.As the following example shows, a Byte object that has a value of 12 does not equal an Int32 object that has a value of 12, because the two objects have different run-time types.
byte value1 = 12; int value2 = 12; object object1 = value1; object object2 = value2; Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", object1, object1.GetType().Name, object2, object2.GetType().Name, object1.Equals(object2)); // The example displays the following output: // 12 (Byte) = 12 (Int32): False
Module Example Public Sub Main() Dim value1 As Byte = 12 Dim value2 As Integer = 12 Dim object1 As Object = value1 Dim object2 As Object = value2 Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", object1, object1.GetType().Name, object2, object2.GetType().Name, object1.Equals(object2)) End Sub End Module ' The example displays the following output: ' 12 (Byte) = 12 (Int32): False
Os valores dos campos público e privado dos dois objetos são iguais.The values of the public and private fields of the two objects are equal. O exemplo a seguir testa a igualdade de valor.The following example tests for value equality. Ele define uma estrutura de
Person
, que é um tipo de valor, e chama o construtor de classePerson
para instanciar dois novos objetosPerson
,person1
eperson2
, que têm o mesmo valor.It defines aPerson
structure, which is a value type, and calls thePerson
class constructor to instantiate two newPerson
objects,person1
andperson2
, which have the same value. Como a saída do exemplo mostra, embora as duas variáveis de objeto façam referência a objetos diferentes,person1
eperson2
são iguais porque têm o mesmo valor para o campo depersonName
privado.As the output from the example shows, although the two object variables refer to different objects,person1
andperson2
are equal because they have the same value for the privatepersonName
field.using System; // Define a value type that does not override Equals. public struct Person { private string personName; public Person(string name) { this.personName = name; } public override string ToString() { return this.personName; } } public struct Example { public static void Main() { Person person1 = new Person("John"); Person person2 = new Person("John"); Console.WriteLine("Calling Equals:"); Console.WriteLine(person1.Equals(person2)); Console.WriteLine("\nCasting to an Object and calling Equals:"); Console.WriteLine(((object) person1).Equals((object) person2)); } } // The example displays the following output: // Calling Equals: // True // // Casting to an Object and calling Equals: // True
' Define a value type that does not override Equals. Public Structure Person Private personName As String Public Sub New(name As String) Me.personName = name End Sub Public Overrides Function ToString() As String Return Me.personName End Function End Structure Module Example Public Sub Main() Dim p1 As New Person("John") Dim p2 As New Person("John") Console.WriteLine("Calling Equals:") Console.WriteLine(p1.Equals(p2)) Console.WriteLine() Console.WriteLine("Casting to an Object and calling Equals:") Console.WriteLine(CObj(p1).Equals(p2)) End Sub End Module ' The example displays the following output: ' Calling Equals: ' True ' ' Casting to an Object and calling Equals: ' True
Como a classe Object é a classe base para todos os tipos na .NET Framework, o método Object.Equals(Object) fornece a comparação de igualdade padrão para todos os outros tipos.Because the Object class is the base class for all types in the .NET Framework, the Object.Equals(Object) method provides the default equality comparison for all other types. No entanto, os tipos geralmente substituem o método Equals para implementar a igualdade de valor.However, types often override the Equals method to implement value equality. Para obter mais informações, consulte as seções notas de chamadores e notas para herdeiros.For more information, see the Notes for Callers and Notes for Inheritors sections.
Observações para o Tempo de Execução do WindowsWindows RuntimeNotes for the Tempo de Execução do WindowsWindows Runtime
Quando você chama a sobrecarga do método Equals(Object) em uma classe no Tempo de Execução do WindowsWindows Runtime, ele fornece o comportamento padrão para classes que não substituem Equals(Object).When you call the Equals(Object) method overload on a class in the Tempo de Execução do WindowsWindows Runtime, it provides the default behavior for classes that don't override Equals(Object). Isso faz parte do suporte que o .NET Framework fornece para o Tempo de Execução do WindowsWindows Runtime (consulte .NET Framework suporte para aplicativos da Windows Store e Windows Runtime).This is part of the support that the .NET Framework provides for the Tempo de Execução do WindowsWindows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). As classes no Tempo de Execução do WindowsWindows Runtime não herdam Objecte, no momento, não implementam um método Equals(Object).Classes in the Tempo de Execução do WindowsWindows Runtime don't inherit Object, and currently don't implement an Equals(Object) method. No entanto, eles parecem ter os métodos ToString, Equals(Object)e GetHashCode ao usá-los em C# seu código ou Visual Basic, e o .NET Framework fornece o comportamento padrão para esses métodos.However, they appear to have ToString, Equals(Object), and GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods.
Observação
Tempo de Execução do WindowsWindows Runtime classes que são gravadas C# no ou Visual Basic podem substituir a sobrecarga do método Equals(Object).classes that are written in C# or Visual Basic can override the Equals(Object) method overload.
Observações para chamadoresNotes for Callers
As classes derivadas freqüentemente substituem o método Object.Equals(Object) para implementar a igualdade de valor.Derived classes frequently override the Object.Equals(Object) method to implement value equality. Além disso, os tipos geralmente fornecem uma sobrecarga de tipo fortemente adicional para o método Equals
, normalmente implementando a interface IEquatable<T>.In addition, types also frequently provide an additional strongly typed overload to the Equals
method, typically by implementing the IEquatable<T> interface. Ao chamar o método de Equals
para testar a igualdade, você deve saber se a instância atual substitui Object.Equals e entender como uma chamada específica para um método de Equals
é resolvida.When you call the Equals
method to test for equality, you should know whether the current instance overrides Object.Equals and understand how a particular call to an Equals
method is resolved. Caso contrário, você pode estar executando um teste para igualdade que seja diferente do que você pretendia, e o método pode retornar um valor inesperado.Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value.
O exemplo a seguir fornece uma ilustração.The following example provides an illustration. Ele cria uma instância de três StringBuilder objetos com cadeias de caracteres idênticas e, em seguida, faz quatro chamadas para Equals
métodos.It instantiates three StringBuilder objects with identical strings, and then makes four calls to Equals
methods. A primeira chamada de método retorna true
e as três false
restantes de retorno.The first method call returns true
, and the remaining three return false
.
using System;
using System.Text;
public class Example
{
public static void Main()
{
StringBuilder sb1 = new StringBuilder("building a string...");
StringBuilder sb2 = new StringBuilder("building a string...");
Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2));
Console.WriteLine("((Object) sb1).Equals(sb2): {0}",
((Object) sb1).Equals(sb2));
Console.WriteLine("Object.Equals(sb1, sb2): {0}",
Object.Equals(sb1, sb2));
Object sb3 = new StringBuilder("building a string...");
Console.WriteLine("\nsb3.Equals(sb2): {0}", sb3.Equals(sb2));
}
}
// The example displays the following output:
// sb1.Equals(sb2): True
// ((Object) sb1).Equals(sb2): False
// Object.Equals(sb1, sb2): False
//
// sb3.Equals(sb2): False
Imports System.Text
Module Example
Public Sub Main()
Dim sb1 As New StringBuilder("building a string...")
Dim sb2 As New StringBuilder("building a string...")
Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2))
Console.WriteLine("CObj(sb1).Equals(sb2): {0}",
CObj(sb1).Equals(sb2))
Console.WriteLine("Object.Equals(sb1, sb2): {0}",
Object.Equals(sb1, sb2))
Console.WriteLine()
Dim sb3 As Object = New StringBuilder("building a string...")
Console.WriteLine("sb3.Equals(sb2): {0}", sb3.Equals(sb2))
End Sub
End Module
' The example displays the following output:
' sb1.Equals(sb2): True
' CObj(sb1).Equals(sb2): False
' Object.Equals(sb1, sb2): False
'
' sb3.Equals(sb2): False
No primeiro caso, a sobrecarga de método de StringBuilder.Equals(StringBuilder) fortemente tipada, que testa a igualdade de valor, é chamada.In the first case, the strongly typed StringBuilder.Equals(StringBuilder) method overload, which tests for value equality, is called. Como as cadeias de caracteres atribuídas aos dois objetos StringBuilder são iguais, o método retorna true
.Because the strings assigned to the two StringBuilder objects are equal, the method returns true
. No entanto, StringBuilder não substitui Object.Equals(Object).However, StringBuilder does not override Object.Equals(Object). Por isso, quando o objeto StringBuilder é convertido em um Object, quando uma instância de StringBuilder é atribuída a uma variável do tipo Objecte quando o método Object.Equals(Object, Object) passa dois objetos StringBuilder, o método de Object.Equals(Object) padrão é chamado.Because of this, when the StringBuilder object is cast to an Object, when a StringBuilder instance is assigned to a variable of type Object, and when the Object.Equals(Object, Object) method is passed two StringBuilder objects, the default Object.Equals(Object) method is called. Como StringBuilder é um tipo de referência, isso é equivalente a passar os dois objetos StringBuilder para o método ReferenceEquals.Because StringBuilder is a reference type, this is equivalent to passing the two StringBuilder objects to the ReferenceEquals method. Embora todos os três objetos StringBuilder contenham cadeias de caracteres idênticas, eles se referem a três objetos distintos.Although all three StringBuilder objects contain identical strings, they refer to three distinct objects. Como resultado, essas três chamadas de método retornam false
.As a result, these three method calls return false
.
Você pode comparar o objeto atual com outro objeto para a igualdade de referência chamando o método ReferenceEquals.You can compare the current object to another object for reference equality by calling the ReferenceEquals method. No Visual Basic, você também pode usar a palavra-chave is
(por exemplo, If Me Is otherObject Then ...
).In Visual Basic, you can also use the is
keyword (for example, If Me Is otherObject Then ...
).
Observações para herdeirosNotes for Inheritors
Quando você define seu próprio tipo, esse tipo herda a funcionalidade definida pelo método Equals
de seu tipo base.When you define your own type, that type inherits the functionality defined by the Equals
method of its base type. A tabela a seguir lista a implementação padrão do método Equals
para as principais categorias de tipos na .NET Framework.The following table lists the default implementation of the Equals
method for the major categories of types in the .NET Framework.
Categoria do tipoType category | Igualdade definida porEquality defined by | CommentsComments |
---|---|---|
Classe derivada diretamente do ObjectClass derived directly from Object | Object.Equals(Object) | Igualdade de referência; equivalente a chamar Object.ReferenceEquals.Reference equality; equivalent to calling Object.ReferenceEquals. |
EstruturaStructure | ValueType.Equals | Igualdade de valor; uma comparação direta de byte por byte ou comparação de campo por campo usando reflexão.Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection. |
EnumeraçãoEnumeration | Enum.Equals | Os valores devem ter o mesmo tipo de enumeração e o mesmo valor subjacente.Values must have the same enumeration type and the same underlying value. |
DelegadoDelegate | MulticastDelegate.Equals | Os delegados devem ter o mesmo tipo com listas de invocação idênticas.Delegates must have the same type with identical invocation lists. |
InterfaceInterface | Object.Equals(Object) | Igualdade de referência.Reference equality. |
Para um tipo de valor, você sempre deve substituir Equals, porque os testes de igualdade que dependem da reflexão oferecem baixo desempenho.For a value type, you should always override Equals, because tests for equality that rely on reflection offer poor performance. Você também pode substituir a implementação padrão de Equals para tipos de referência para testar a igualdade de valor em vez de igualdade de referência e definir o significado preciso de igualdade de valor.You can also override the default implementation of Equals for reference types to test for value equality instead of reference equality and to define the precise meaning of value equality. Essas implementações de Equals retornam true
se os dois objetos tiverem o mesmo valor, mesmo que eles não sejam a mesma instância.Such implementations of Equals return true
if the two objects have the same value, even if they are not the same instance. O implementador do tipo decide o que constitui o valor de um objeto, mas normalmente é alguns ou todos os dados armazenados nas variáveis de instância do objeto.The type's implementer decides what constitutes an object's value, but it is typically some or all the data stored in the instance variables of the object. Por exemplo, o valor de um objeto String é baseado nos caracteres da cadeia de caracteres; o método String.Equals(Object) substitui o método Object.Equals(Object) para retornar true
para quaisquer duas instâncias de cadeia de caracteres que contenham os mesmos caracteres na mesma ordem.For example, the value of a String object is based on the characters of the string; the String.Equals(Object) method overrides the Object.Equals(Object) method to return true
for any two string instances that contain the same characters in the same order.
O exemplo a seguir mostra como substituir o método Object.Equals(Object) para testar a igualdade de valor.The following example shows how to override the Object.Equals(Object) method to test for value equality. Ele substitui o método Equals para a classe Person
.It overrides the Equals method for the Person
class. Se Person
aceitou sua implementação de classe base de igualdade, dois objetos Person
seriam iguais somente se eles fizerem referência a um único objeto.If Person
accepted its base class implementation of equality, two Person
objects would be equal only if they referenced a single object. No entanto, nesse caso, dois objetos Person
são iguais se tiverem o mesmo valor para a propriedade Person.Id
.However, in this case, two Person
objects are equal if they have the same value for the Person.Id
property.
public class Person
{
private string idNumber;
private string personName;
public Person(string name, string id)
{
this.personName = name;
this.idNumber = id;
}
public override bool Equals(Object obj)
{
Person personObj = obj as Person;
if (personObj == null)
return false;
else
return idNumber.Equals(personObj.idNumber);
}
public override int GetHashCode()
{
return this.idNumber.GetHashCode();
}
}
public class Example
{
public static void Main()
{
Person p1 = new Person("John", "63412895");
Person p2 = new Person("Jack", "63412895");
Console.WriteLine(p1.Equals(p2));
Console.WriteLine(Object.Equals(p1, p2));
}
}
// The example displays the following output:
// True
// True
Public Class Person
Private idNumber As String
Private personName As String
Public Sub New(name As String, id As String)
Me.personName = name
Me.idNumber = id
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim personObj As Person = TryCast(obj, Person)
If personObj Is Nothing Then
Return False
Else
Return idNumber.Equals(personObj.idNumber)
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.idNumber.GetHashCode()
End Function
End Class
Module Example
Public Sub Main()
Dim p1 As New Person("John", "63412895")
Dim p2 As New Person("Jack", "63412895")
Console.WriteLine(p1.Equals(p2))
Console.WriteLine(Object.Equals(p1, p2))
End Sub
End Module
' The example displays the following output:
' True
' True
Além de substituir Equals, você pode implementar a interface IEquatable<T> para fornecer um teste fortemente tipado para igualdade.In addition to overriding Equals, you can implement the IEquatable<T> interface to provide a strongly typed test for equality.
As instruções a seguir devem ser verdadeiras para todas as implementações do método Equals(Object).The following statements must be true for all implementations of the Equals(Object) method. Na lista, x
, y
e z
representam referências de objeto que não são nulas.In the list, x
, y
, and z
represent object references that are not null.
x.Equals(x)
retornatrue
, exceto nos casos que envolvem tipos de ponto flutuante.x.Equals(x)
returnstrue
, except in cases that involve floating-point types. Consulte ISO/IEC/IEEE 60559:2011, tecnologia da informação--sistemas de microprocessador--aritmética de ponto flutuante.See ISO/IEC/IEEE 60559:2011, Information technology -- Microprocessor Systems -- Floating-Point arithmetic.x.Equals(y)
retorna o mesmo valor quey.Equals(x)
.x.Equals(y)
returns the same value asy.Equals(x)
.x.Equals(y)
retornarátrue
sex
ey
foremNaN
.x.Equals(y)
returnstrue
if bothx
andy
areNaN
.Se
(x.Equals(y) && y.Equals(z))
retornartrue
,x.Equals(z)
retornarátrue
.If(x.Equals(y) && y.Equals(z))
returnstrue
, thenx.Equals(z)
returnstrue
.As chamadas sucessivas para
x.Equals(y)
retornam o mesmo valor, desde que os objetos referenciados porx
ey
não sejam modificados.Successive calls tox.Equals(y)
return the same value as long as the objects referenced byx
andy
are not modified.x.Equals(null)
retornafalse
.x.Equals(null)
returnsfalse
.
Implementações de Equals não devem gerar exceções; Eles sempre devem retornar um valor.Implementations of Equals must not throw exceptions; they should always return a value. Por exemplo, se obj
for null
, o método Equals deverá retornar false
em vez de lançar um ArgumentNullException.For example, if obj
is null
, the Equals method should return false
instead of throwing an ArgumentNullException.
Siga estas diretrizes ao substituir Equals(Object):Follow these guidelines when overriding Equals(Object):
Os tipos que implementam IComparable devem substituir Equals(Object).Types that implement IComparable must override Equals(Object).
Os tipos que substituem Equals(Object) também devem substituir GetHashCode; caso contrário, as tabelas de hash podem não funcionar corretamente.Types that override Equals(Object) must also override GetHashCode; otherwise, hash tables might not work correctly.
Você deve considerar a implementação da interface IEquatable<T> para dar suporte a testes fortemente tipados para igualdade.You should consider implementing the IEquatable<T> interface to support strongly typed tests for equality. Sua implementação de IEquatable<T>.Equals deve retornar resultados que são consistentes com Equals.Your IEquatable<T>.Equals implementation should return results that are consistent with Equals.
Se a linguagem de programação der suporte à sobrecarga de operador e você sobrecarregar o operador de igualdade para um determinado tipo, você também deverá substituir o método Equals(Object) para retornar o mesmo resultado que o operador de igualdade.If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override the Equals(Object) method to return the same result as the equality operator. Isso ajuda a garantir que o código da biblioteca de classes que usa Equals (como ArrayList e Hashtable) se comporta de maneira consistente com o modo como o operador de igualdade é usado pelo código do aplicativo.This helps ensure that class library code that uses Equals (such as ArrayList and Hashtable) behaves in a manner that is consistent with the way the equality operator is used by application code.
Diretrizes para tipos de referênciaGuidelines for Reference Types
As diretrizes a seguir se aplicam à substituição de Equals(Object) para um tipo de referência:The following guidelines apply to overriding Equals(Object) for a reference type:
Considere substituir Equals se a semântica do tipo for baseada no fato de que o tipo representa alguns valores.Consider overriding Equals if the semantics of the type are based on the fact that the type represents some value(s).
A maioria dos tipos de referência não deve sobrecarregar o operador de igualdade, mesmo que eles substituam Equals.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 tem como objetivo ter semântica de valor, como um tipo de número complexo, você deve substituir o operador de igualdade.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.
Você não deve substituir Equals em um tipo de referência mutável.You should not override Equals on a mutable reference type. Isso ocorre porque a substituição de Equals requer que você também substitua o método GetHashCode, conforme discutido na seção anterior.This is because overriding Equals requires that you also override the GetHashCode method, as discussed in the previous section. Isso significa que o código hash de uma instância de um tipo de referência mutável pode ser alterado durante seu tempo de vida, o que pode fazer com que o objeto seja perdido em uma tabela de hash.This means that the hash code of an instance of a mutable reference type can change during its lifetime, which can cause the object to be lost in a hash table.
Diretrizes para tipos de valorGuidelines for Value Types
As diretrizes a seguir se aplicam à substituição de Equals(Object) para um tipo de valor:The following guidelines apply to overriding Equals(Object) for a value type:
Se você estiver definindo um tipo de valor que inclui um ou mais campos cujos valores são tipos de referência, você deve substituir Equals(Object).If you are defining a value type that includes one or more fields whose values are reference types, you should override Equals(Object). A implementação de Equals(Object) fornecida pelo ValueType executa uma comparação byte a byte para tipos de valor cujos campos são todos os tipos de valor, mas ele usa a reflexão para executar uma comparação campo a campo de tipos de valor cujos campos incluem tipos de referência.The Equals(Object) implementation provided by ValueType performs a byte-by-byte comparison for value types whose fields are all value types, but it uses reflection to perform a field-by-field comparison of value types whose fields include reference types.
Se você substituir Equals e sua linguagem de desenvolvimento der suporte à sobrecarga de operador, você deverá sobrecarregar o operador de igualdade.If you override Equals and your development language supports operator overloading, you must overload the equality operator.
Você deve implementar a interface IEquatable<T>.You should implement the IEquatable<T> interface. Chamar o método de IEquatable<T>.Equals fortemente tipado evita a conversão de boxing no argumento
obj
.Calling the strongly typed IEquatable<T>.Equals method avoids boxing theobj
argument.
Veja também
Equals(Object, Object)
Determina se as instâncias de objeto especificadas são consideradas iguais.Determines whether the specified object instances are considered equal.
public:
static bool Equals(System::Object ^ objA, System::Object ^ objB);
public static bool Equals (object objA, object objB);
static member Equals : obj * obj -> bool
Public Shared Function Equals (objA As Object, objB As Object) As Boolean
Parâmetros
- objA
- Object
O primeiro objeto a ser comparado.The first object to compare.
- objB
- Object
O segundo objeto a ser comparado.The second object to compare.
Retornos
true
se os objetos forem considerados iguais; caso contrário, false
.true
if the objects are considered equal; otherwise, false
. Se objA
e objB
forem null, o método retornará true
.If both objA
and objB
are null, the method returns true
.
Exemplos
O exemplo a seguir ilustra o método Equals(Object, Object) e o compara com o método ReferenceEquals.The following example illustrates the Equals(Object, Object) method and compares it with the ReferenceEquals method.
using System;
public class Example
{
public static void Main()
{
Dog m1 = new Dog("Alaskan Malamute");
Dog m2 = new Dog("Alaskan Malamute");
Dog g1 = new Dog("Great Pyrenees");
Dog g2 = g1;
Dog d1 = new Dog("Dalmation");
Dog n1 = null;
Dog n2 = null;
Console.WriteLine("null = null: {0}", Object.Equals(n1, n2));
Console.WriteLine("null Reference Equals null: {0}\n", Object.ReferenceEquals(n1, n2));
Console.WriteLine("{0} = {1}: {2}", g1, g2, Object.Equals(g1, g2));
Console.WriteLine("{0} Reference Equals {1}: {2}\n", g1, g2, Object.ReferenceEquals(g1, g2));
Console.WriteLine("{0} = {1}: {2}", m1, m2, Object.Equals(m1, m2));
Console.WriteLine("{0} Reference Equals {1}: {2}\n", m1, m2, Object.ReferenceEquals(m1, m2));
Console.WriteLine("{0} = {1}: {2}", m1, d1, Object.Equals(m1, d1));
Console.WriteLine("{0} Reference Equals {1}: {2}", m1, d1, Object.ReferenceEquals(m1, d1));
}
}
public class Dog
{
// Public field.
public string Breed;
// Class constructor.
public Dog(string dogBreed)
{
this.Breed = dogBreed;
}
public override bool Equals(Object obj)
{
if (obj == null || !(obj is Dog))
return false;
else
return this.Breed == ((Dog) obj).Breed;
}
public override int GetHashCode()
{
return this.Breed.GetHashCode();
}
public override string ToString()
{
return this.Breed;
}
}
// The example displays the following output:
// null = null: True
// null Reference Equals null: True
//
// Great Pyrenees = Great Pyrenees: True
// Great Pyrenees Reference Equals Great Pyrenees: True
//
// Alaskan Malamute = Alaskan Malamute: True
// Alaskan Malamute Reference Equals Alaskan Malamute: False
//
// Alaskan Malamute = Dalmation: False
// Alaskan Malamute Reference Equals Dalmation: False
Module Example
Public Sub Main()
Dim m1 As New Dog("Alaskan Malamute")
Dim m2 As New Dog("Alaskan Malamute")
Dim g1 As New Dog("Great Pyrenees")
Dim g2 As Dog = g1
Dim d1 As New Dog("Dalmation")
Dim n1 As Dog = Nothing
Dim n2 As Dog = Nothing
Console.WriteLine("null = null: {0}", Object.Equals(n1, n2))
Console.WriteLine("null Reference Equals null: {0}", Object.ReferenceEquals(n1, n2))
Console.WriteLine()
Console.WriteLine("{0} = {1}: {2}", g1, g2, Object.Equals(g1, g2))
Console.WriteLine("{0} Reference Equals {1}: {2}", g1, g2, Object.ReferenceEquals(g1, g2))
Console.WriteLine()
Console.WriteLine("{0} = {1}: {2}", m1, m2, Object.Equals(m1, m2))
Console.WriteLine("{0} Reference Equals {1}: {2}", m1, m2, Object.ReferenceEquals(m1, m2))
Console.WriteLine()
Console.WriteLine("{0} = {1}: {2}", m1, d1, Object.Equals(m1, d1))
Console.WriteLine("{0} Reference Equals {1}: {2}", m1, d1, Object.ReferenceEquals(m1, d1))
End Sub
End Module
Public Class Dog
' Public field.
Public Breed As String
' Class constructor.
Public Sub New(dogBreed As String)
Me.Breed = dogBreed
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing OrElse Not typeof obj Is Dog Then
Return False
Else
Return Me.Breed = CType(obj, Dog).Breed
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.Breed.GetHashCode()
End Function
Public Overrides Function ToString() As String
Return Me.Breed
End Function
End Class
' The example displays the following output:
' null = null: True
' null Reference Equals null: True
'
' Great Pyrenees = Great Pyrenees: True
' Great Pyrenees Reference Equals Great Pyrenees: True
'
' Alaskan Malamute = Alaskan Malamute: True
' Alaskan Malamute Reference Equals Alaskan Malamute: False
'
' Alaskan Malamute = Dalmation: False
' Alaskan Malamute Reference Equals Dalmation: False
Comentários
O método estático Equals(Object, Object) indica se dois objetos, objA
e objB
, são iguais.The static Equals(Object, Object) method indicates whether two objects, objA
and objB
, are equal. Ele também permite testar objetos cujo valor é nulo para igualdade.It also enables you to test objects whose value is null for equality. Ele compara objA
e objB
para igualdade da seguinte maneira:It compares objA
and objB
for equality as follows:
Ele determina se os dois objetos representam a mesma referência de objeto.It determines whether the two objects represent the same object reference. Se isso for feito, o método retornará
true
.If they do, the method returnstrue
. Esse teste é equivalente a chamar o método ReferenceEquals.This test is equivalent to calling the ReferenceEquals method. Além disso, seobjA
eobjB
forem nulos, o método retornarátrue
.In addition, if bothobjA
andobjB
are null, the method returnstrue
.Ele determina se
objA
ouobjB
é nulo.It determines whether eitherobjA
orobjB
is null. Nesse caso, ele retornafalse
.If so, it returnsfalse
.Se os dois objetos não representarem a mesma referência de objeto e nenhum for nulo, ele chamará
objA
.Equals
(objB
) e retorna o resultado.If the two objects do not represent the same object reference and neither is null, it callsobjA
.Equals
(objB
) and returns the result. Isso significa que, seobjA
substitui o método Object.Equals(Object), essa substituição é chamada.This means that ifobjA
overrides the Object.Equals(Object) method, this override is called.