Object.Equals Metoda
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Określa, czy dwa wystąpienia obiektu są takie same.
Przeciążenia
Equals(Object) |
Określa, czy dany obiekt jest taki sam, jak bieżący obiekt. |
Equals(Object, Object) |
Określa, czy określone wystąpienia obiektów są traktowane jako równe. |
Equals(Object)
Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.
public:
virtual bool Equals(System::Object ^ obj);
public virtual bool Equals (object obj);
public virtual bool Equals (object? obj);
abstract member Equals : obj -> bool
override this.Equals : obj -> bool
Public Overridable Function Equals (obj As Object) As Boolean
Parametry
- obj
- Object
Obiekt do porównania z bieżącym obiektem.
Zwraca
true
jeśli określony obiekt jest równy bieżącemu obiektowi; w przeciwnym razie , false
.
Przykłady
W poniższym przykładzie pokazano klasę, która zastępuje Equals metodę Point
w celu zapewnienia równości wartości, oraz klasę pochodzącą Point3D
z Point
klasy . Ponieważ Point
przesłonięcia Object.Equals(Object) do testowania równości wartości, metoda nie jest wywoływana Object.Equals(Object) . Jednak wywołania Point.Equals
, Point3D.Equals
ponieważ Point
implementuje Object.Equals(Object) w sposób zapewniający równość wartości.
using System;
class Point
{
protected int x, y;
public Point() : this(0, 0)
{ }
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override bool Equals(Object obj)
{
//Check for null and compare run-time types.
if ((obj == null) || ! this.GetType().Equals(obj.GetType()))
{
return false;
}
else {
Point p = (Point) obj;
return (x == p.x) && (y == p.y);
}
}
public override int GetHashCode()
{
return (x << 2) ^ y;
}
public override string ToString()
{
return String.Format("Point({0}, {1})", x, y);
}
}
sealed class Point3D: Point
{
int z;
public Point3D(int x, int y, int z) : base(x, y)
{
this.z = z;
}
public override bool Equals(Object obj)
{
Point3D pt3 = obj as Point3D;
if (pt3 == null)
return false;
else
return base.Equals((Point)obj) && z == pt3.z;
}
public override int GetHashCode()
{
return (base.GetHashCode() << 2) ^ z;
}
public override String ToString()
{
return String.Format("Point({0}, {1}, {2})", x, y, z);
}
}
class Example
{
public static void Main()
{
Point point2D = new Point(5, 5);
Point3D point3Da = new Point3D(5, 5, 2);
Point3D point3Db = new Point3D(5, 5, 2);
Point3D point3Dc = new Point3D(5, 5, -1);
Console.WriteLine("{0} = {1}: {2}",
point2D, point3Da, point2D.Equals(point3Da));
Console.WriteLine("{0} = {1}: {2}",
point2D, point3Db, point2D.Equals(point3Db));
Console.WriteLine("{0} = {1}: {2}",
point3Da, point3Db, point3Da.Equals(point3Db));
Console.WriteLine("{0} = {1}: {2}",
point3Da, point3Dc, point3Da.Equals(point3Dc));
}
}
// The example displays the following output:
// Point(5, 5) = Point(5, 5, 2): False
// Point(5, 5) = Point(5, 5, 2): False
// Point(5, 5, 2) = Point(5, 5, 2): True
// Point(5, 5, 2) = Point(5, 5, -1): False
type Point(x, y) =
new () = Point(0, 0)
member _.X = x
member _.Y = y
override _.Equals(obj) =
//Check for null and compare run-time types.
match obj with
| :? Point as p ->
x = p.X && y = p.Y
| _ ->
false
override _.GetHashCode() =
(x <<< 2) ^^^ y
override _.ToString() =
$"Point({x}, {y})"
type Point3D(x, y, z) =
inherit Point(x, y)
member _.Z = z
override _.Equals(obj) =
match obj with
| :? Point3D as pt3 ->
base.Equals(pt3 :> Point) && z = pt3.Z
| _ ->
false
override _.GetHashCode() =
(base.GetHashCode() <<< 2) ^^^ z
override _.ToString() =
$"Point({x}, {y}, {z})"
let point2D = Point(5, 5)
let point3Da = Point3D(5, 5, 2)
let point3Db = Point3D(5, 5, 2)
let point3Dc = Point3D(5, 5, -1)
printfn $"{point2D} = {point3Da}: {point2D.Equals point3Da}"
printfn $"{point2D} = {point3Db}: {point2D.Equals point3Db}"
printfn $"{point3Da} = {point3Db}: {point3Da.Equals point3Db}"
printfn $"{point3Da} = {point3Dc}: {point3Da.Equals point3Dc}"
// The example displays the following output:
// Point(5, 5) = Point(5, 5, 2): False
// Point(5, 5) = Point(5, 5, 2): False
// Point(5, 5, 2) = Point(5, 5, 2): True
// Point(5, 5, 2) = Point(5, 5, -1): False
Class Point
Protected x, y As Integer
Public Sub New()
Me.x = 0
Me.y = 0
End Sub
Public Sub New(x As Integer, y As Integer)
Me.x = x
Me.y = y
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
' Check for null and compare run-time types.
If obj Is Nothing OrElse Not Me.GetType().Equals(obj.GetType()) Then
Return False
Else
Dim p As Point = DirectCast(obj, Point)
Return x = p.x AndAlso y = p.y
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return (x << 2) XOr y
End Function
Public Overrides Function ToString() As String
Return String.Format("Point({0}, {1})", x, y)
End Function
End Class
Class Point3D : Inherits Point
Private z As Integer
Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer)
MyBase.New(x, y)
Me.z = Z
End Sub
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Dim pt3 As Point3D = TryCast(obj, Point3D)
If pt3 Is Nothing Then
Return False
Else
Return MyBase.Equals(CType(pt3, Point)) AndAlso z = pt3.Z
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return (MyBase.GetHashCode() << 2) XOr z
End Function
Public Overrides Function ToString() As String
Return String.Format("Point({0}, {1}, {2})", x, y, z)
End Function
End Class
Module Example
Public Sub Main()
Dim point2D As New Point(5, 5)
Dim point3Da As New Point3D(5, 5, 2)
Dim point3Db As New Point3D(5, 5, 2)
Dim point3Dc As New Point3D(5, 5, -1)
Console.WriteLine("{0} = {1}: {2}",
point2D, point3Da, point2D.Equals(point3Da))
Console.WriteLine("{0} = {1}: {2}",
point2D, point3Db, point2D.Equals(point3Db))
Console.WriteLine("{0} = {1}: {2}",
point3Da, point3Db, point3Da.Equals(point3Db))
Console.WriteLine("{0} = {1}: {2}",
point3Da, point3Dc, point3Da.Equals(point3Dc))
End Sub
End Module
' The example displays the following output
' Point(5, 5) = Point(5, 5, 2): False
' Point(5, 5) = Point(5, 5, 2): False
' Point(5, 5, 2) = Point(5, 5, 2): True
' Point(5, 5, 2) = Point(5, 5, -1): False
Metoda Point.Equals
sprawdza, czy obj
argument nie ma wartości null i odwołuje się do wystąpienia tego samego typu co ten obiekt. Jeśli sprawdzanie zakończy się niepowodzeniem, metoda zwraca wartość false
.
Metoda Point.Equals
wywołuje metodę , GetType aby określić, czy typy czasu wykonywania dwóch obiektów są identyczne. Jeśli metoda użyła sprawdzania formularza obj is Point
w języku C# lub TryCast(obj, Point)
w Visual Basic, sprawdzanie zwróci true
w przypadkach, obj
gdy jest wystąpieniem klasy pochodnej Point
klasy , mimo że obj
bieżące wystąpienie nie jest tym samym typem czasu wykonywania. Po sprawdzeniu, że oba obiekty są tego samego typu, metoda rzutuje obj
typ Point
i zwraca wynik porównania pól wystąpienia dwóch obiektów.
W Point3D.Equals
systemie dziedziczona Point.Equals
metoda, która zastępuje Object.Equals(Object)metodę , jest wywoływana przed wykonaniem czegokolwiek innego. Ponieważ Point3D
jest to zapieczętowana klasa (NotInheritable
w Visual Basic), sprawdzanie w formularzu obj is Point
w języku C# lub TryCast(obj, Point)
w Visual Basic jest odpowiednie, aby upewnić się, że obj
jest to Point3D
obiekt. Jeśli jest Point3D
to obiekt, jest rzutowany do Point
obiektu i przekazywany do implementacji klasy bazowej klasy Equals. Tylko wtedy, gdy dziedziczona Point.Equals
metoda zwraca true
, metoda porównuje z
pola wystąpienia wprowadzone w klasie pochodnej.
W poniższym przykładzie zdefiniowano klasę Rectangle
, która wewnętrznie implementuje prostokąt jako dwa Point
obiekty. Klasa Rectangle
zastępuje Object.Equals(Object) również element , aby zapewnić równość wartości.
using System;
class Rectangle
{
private Point a, b;
public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY)
{
this.a = new Point(upLeftX, upLeftY);
this.b = new Point(downRightX, downRightY);
}
public override bool Equals(Object obj)
{
// Perform an equality check on two rectangles (Point object pairs).
if (obj == null || GetType() != obj.GetType())
return false;
Rectangle r = (Rectangle)obj;
return a.Equals(r.a) && b.Equals(r.b);
}
public override int GetHashCode()
{
return Tuple.Create(a, b).GetHashCode();
}
public override String ToString()
{
return String.Format("Rectangle({0}, {1}, {2}, {3})",
a.x, a.y, b.x, b.y);
}
}
class Point
{
internal int x;
internal int y;
public Point(int X, int Y)
{
this.x = X;
this.y = Y;
}
public override bool Equals (Object obj)
{
// Performs an equality check on two points (integer pairs).
if (obj == null || GetType() != obj.GetType()) return false;
Point p = (Point)obj;
return (x == p.x) && (y == p.y);
}
public override int GetHashCode()
{
return Tuple.Create(x, y).GetHashCode();
}
}
class Example
{
public static void Main()
{
Rectangle r1 = new Rectangle(0, 0, 100, 200);
Rectangle r2 = new Rectangle(0, 0, 100, 200);
Rectangle r3 = new Rectangle(0, 0, 150, 200);
Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2));
Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3));
Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3));
}
}
// The example displays the following output:
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
type Point(x, y) =
member _.X = x
member _.Y = y
override _.Equals(obj) =
// Performs an equality check on two points (integer pairs).
match obj with
| :? Point as p ->
x = p.X && y = p.Y
| _ ->
false
override _.GetHashCode() =
(x, y).GetHashCode()
type Rectangle(upLeftX, upLeftY, downRightX, downRightY) =
let a = Point(upLeftX, upLeftY)
let b = Point(downRightX, downRightY)
member _.UpLeft = a
member _.DownRight = b
override _.Equals(obj) =
// Perform an equality check on two rectangles (Point object pairs).
match obj with
| :? Rectangle as r ->
a.Equals(r.UpLeft) && b.Equals(r.DownRight)
| _ ->
false
override _.GetHashCode() =
(a, b).GetHashCode()
override _.ToString() =
$"Rectangle({a.X}, {a.Y}, {b.X}, {b.Y})"
let r1 = Rectangle(0, 0, 100, 200)
let r2 = Rectangle(0, 0, 100, 200)
let r3 = Rectangle(0, 0, 150, 200)
printfn $"{r1} = {r2}: {r1.Equals r2}"
printfn $"{r1} = {r3}: {r1.Equals r3}"
printfn $"{r2} = {r3}: {r2.Equals r3}"
// The example displays the following output:
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
Class Rectangle
Private a, b As Point
Public Sub New(ByVal upLeftX As Integer, ByVal upLeftY As Integer, _
ByVal downRightX As Integer, ByVal downRightY As Integer)
Me.a = New Point(upLeftX, upLeftY)
Me.b = New Point(downRightX, downRightY)
End Sub
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
' Performs an equality check on two rectangles (Point object pairs).
If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
Return False
End If
Dim r As Rectangle = CType(obj, Rectangle)
Return a.Equals(r.a) AndAlso b.Equals(r.b)
End Function
Public Overrides Function GetHashCode() As Integer
Return Tuple.Create(a, b).GetHashCode()
End Function
Public Overrides Function ToString() As String
Return String.Format("Rectangle({0}, {1}, {2}, {3})",
a.x, a.y, b.x, b.y)
End Function
End Class
Class Point
Friend x As Integer
Friend y As Integer
Public Sub New(ByVal X As Integer, ByVal Y As Integer)
Me.x = X
Me.y = Y
End Sub
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
' Performs an equality check on two points (integer pairs).
If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
Return False
Else
Dim p As Point = CType(obj, Point)
Return x = p.x AndAlso y = p.y
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return Tuple.Create(x, y).GetHashCode()
End Function
End Class
Class Example
Public Shared Sub Main()
Dim r1 As New Rectangle(0, 0, 100, 200)
Dim r2 As New Rectangle(0, 0, 100, 200)
Dim r3 As New Rectangle(0, 0, 150, 200)
Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2))
Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3))
Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3))
End Sub
End Class
' The example displays the following output:
' Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
' Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
' Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
Niektóre języki, takie jak C# i Visual Basic obsługują przeciążenie operatora. Gdy typ przeciąża operatora równości, musi również zastąpić metodę Equals(Object) , aby zapewnić tę samą funkcjonalność. Jest to zwykle realizowane przez napisanie Equals(Object) metody pod względem przeciążonego operatora równości, jak w poniższym przykładzie.
using System;
public struct Complex
{
public double re, im;
public override bool Equals(Object obj)
{
return obj is Complex && this == (Complex)obj;
}
public override int GetHashCode()
{
return Tuple.Create(re, im).GetHashCode();
}
public static bool operator ==(Complex x, Complex y)
{
return x.re == y.re && x.im == y.im;
}
public static bool operator !=(Complex x, Complex y)
{
return !(x == y);
}
public override String ToString()
{
return String.Format("({0}, {1})", re, im);
}
}
class MyClass
{
public static void Main()
{
Complex cmplx1, cmplx2;
cmplx1.re = 4.0;
cmplx1.im = 1.0;
cmplx2.re = 2.0;
cmplx2.im = 1.0;
Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 != cmplx2);
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2));
cmplx2.re = 4.0;
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 == cmplx2);
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2));
}
}
// The example displays the following output:
// (4, 1) <> (2, 1): True
// (4, 1) = (2, 1): False
// (4, 1) = (4, 1): True
// (4, 1) = (4, 1): True
[<Struct; CustomEquality; NoComparison>]
type Complex =
val mutable re: double
val mutable im: double
override this.Equals(obj) =
match obj with
| :? Complex as c when c = this -> true
| _ -> false
override this.GetHashCode() =
(this.re, this.im).GetHashCode()
override this.ToString() =
$"({this.re}, {this.im})"
static member op_Equality (x: Complex, y: Complex) =
x.re = y.re && x.im = y.im
static member op_Inequality (x: Complex, y: Complex) =
x = y |> not
let mutable cmplx1 = Complex()
let mutable cmplx2 = Complex()
cmplx1.re <- 4.0
cmplx1.im <- 1.0
cmplx2.re <- 2.0
cmplx2.im <- 1.0
printfn $"{cmplx1} <> {cmplx2}: {cmplx1 <> cmplx2}"
printfn $"{cmplx1} = {cmplx2}: {cmplx1.Equals cmplx2}"
cmplx2.re <- 4.0
printfn $"{cmplx1} = {cmplx2}: {cmplx1 = cmplx2}"
printfn $"{cmplx1} = {cmplx2}: {cmplx1.Equals cmplx2}"
// The example displays the following output:
// (4, 1) <> (2, 1): True
// (4, 1) = (2, 1): False
// (4, 1) = (4, 1): True
// (4, 1) = (4, 1): True
Public Structure Complex
Public re, im As Double
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
Return TypeOf obj Is Complex AndAlso Me = CType(obj, Complex)
End Function
Public Overrides Function GetHashCode() As Integer
Return Tuple.Create(re, im).GetHashCode()
End Function
Public Shared Operator = (x As Complex, y As Complex) As Boolean
Return x.re = y.re AndAlso x.im = y.im
End Operator
Public Shared Operator <> (x As Complex, y As Complex) As Boolean
Return Not (x = y)
End Operator
Public Overrides Function ToString() As String
Return String.Format("({0}, {1})", re, im)
End Function
End Structure
Class Example
Public Shared Sub Main()
Dim cmplx1, cmplx2 As Complex
cmplx1.re = 4.0
cmplx1.im = 1.0
cmplx2.re = 2.0
cmplx2.im = 1.0
Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 <> cmplx2)
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))
cmplx2.re = 4.0
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 = cmplx2)
Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))
End Sub
End Class
' The example displays the following output:
' (4, 1) <> (2, 1): True
' (4, 1) = (2, 1): False
' (4, 1) = (4, 1): True
' (4, 1) = (4, 1): True
Ponieważ Complex
jest typem wartości, nie można go uzyskać. W związku z tym zastąpienie Equals(Object) metody nie musi wywoływać GetType w celu określenia dokładnego typu czasu wykonywania każdego obiektu, ale może zamiast tego użyć is
operatora w języku C# lub TypeOf
operatora w Visual Basic, aby sprawdzić typ parametruobj
.
Uwagi
Typ porównania między bieżącym wystąpieniem a obj
parametrem zależy od tego, czy bieżące wystąpienie jest typem referencyjnym, czy typem wartości.
Jeśli bieżące wystąpienie jest typem odwołania, Equals(Object) metoda sprawdza równość odwołań, a wywołanie metody jest równoważne wywołaniu Equals(Object) metody do ReferenceEquals metody . Równość odwołań oznacza, że zmienne obiektu, które są porównywane, odwołują się do tego samego obiektu. Poniższy przykład ilustruje wynik takiego porównania. Definiuje klasę, która jest typem
Person
odwołania, i wywołujePerson
konstruktora klasy w celu utworzenia wystąpienia dwóch nowychPerson
obiektówperson1a
iperson2
, które mają tę samą wartość. Przypisujeperson1a
również do innej zmiennej obiektu .person1b
Jak pokazano w danych wyjściowych z przykładu, iperson1b
są równe,person1a
ponieważ odwołują się do tego samego obiektu. Jednak iperson2
nie są równe,person1a
chociaż mają tę samą wartość.using System; // Define a reference type that does not override Equals. public class Person { private string personName; public Person(string name) { this.personName = name; } public override string ToString() { return this.personName; } } public class Example { public static void Main() { Person person1a = new Person("John"); Person person1b = person1a; Person person2 = new Person(person1a.ToString()); Console.WriteLine("Calling Equals:"); Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b)); Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2)); Console.WriteLine("\nCasting to an Object and calling Equals:"); Console.WriteLine("person1a and person1b: {0}", ((object) person1a).Equals((object) person1b)); Console.WriteLine("person1a and person2: {0}", ((object) person1a).Equals((object) person2)); } } // The example displays the following output: // person1a and person1b: True // person1a and person2: False // // Casting to an Object and calling Equals: // person1a and person1b: True // person1a and person2: False
// Define a reference type that does not override Equals. type Person(name) = override _.ToString() = name let person1a = Person "John" let person1b = person1a let person2 = Person(string person1a) printfn "Calling Equals:" printfn $"person1a and person1b: {person1a.Equals person1b}" printfn $"person1a and person2: {person1a.Equals person2}" printfn "\nCasting to an Object and calling Equals:" printfn $"person1a and person1b: {(person1a :> obj).Equals(person1b :> obj)}" printfn $"person1a and person2: {(person1a :> obj).Equals(person2 :> obj)}" // The example displays the following output: // person1a and person1b: True // person1a and person2: False // // Casting to an Object and calling Equals: // person1a and person1b: True // person1a and person2: False
' Define a reference type that does not override Equals. Public Class Person Private personName As String Public Sub New(name As String) Me.personName = name End Sub Public Overrides Function ToString() As String Return Me.personName End Function End Class Module Example Public Sub Main() Dim person1a As New Person("John") Dim person1b As Person = person1a Dim person2 As New Person(person1a.ToString()) Console.WriteLine("Calling Equals:") Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b)) Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2)) Console.WriteLine() Console.WriteLine("Casting to an Object and calling Equals:") Console.WriteLine("person1a and person1b: {0}", CObj(person1a).Equals(CObj(person1b))) Console.WriteLine("person1a and person2: {0}", CObj(person1a).Equals(CObj(person2))) End Sub End Module ' The example displays the following output: ' Calling Equals: ' person1a and person1b: True ' person1a and person2: False ' ' Casting to an Object and calling Equals: ' person1a and person1b: True ' person1a and person2: False
Jeśli bieżące wystąpienie jest typem wartości, Equals(Object) metoda sprawdza równość wartości. Równość wartości oznacza następujące elementy:
Dwa obiekty są tego samego typu. Jak pokazano w poniższym przykładzie, Byte obiekt o wartości 12 nie jest równy Int32 obiektowi o wartości 12, ponieważ dwa obiekty mają różne typy czasu wykonywania.
byte value1 = 12; int value2 = 12; object object1 = value1; object object2 = value2; Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", object1, object1.GetType().Name, object2, object2.GetType().Name, object1.Equals(object2)); // The example displays the following output: // 12 (Byte) = 12 (Int32): False
let value1 = 12uy let value2 = 12 let object1 = value1 :> obj let object2 = value2 :> obj printfn $"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals object2}" // The example displays the following output: // 12 (Byte) = 12 (Int32): False
Module Example Public Sub Main() Dim value1 As Byte = 12 Dim value2 As Integer = 12 Dim object1 As Object = value1 Dim object2 As Object = value2 Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", object1, object1.GetType().Name, object2, object2.GetType().Name, object1.Equals(object2)) End Sub End Module ' The example displays the following output: ' 12 (Byte) = 12 (Int32): False
Wartości pól publicznych i prywatnych dwóch obiektów są równe. Poniższy przykład sprawdza równość wartości. Definiuje strukturę, która jest typem
Person
wartości, i wywołujePerson
konstruktor klasy w celu utworzenia wystąpienia dwóch nowychPerson
obiektówperson1
iperson2
, które mają tę samą wartość. Jak pokazuje dane wyjściowe z przykładu, chociaż dwie zmienne obiektu odwołują się do różnych obiektów iperson2
są równe,person1
ponieważ mają taką samą wartość dla pola prywatnegopersonName
.using System; // Define a value type that does not override Equals. public struct Person { private string personName; public Person(string name) { this.personName = name; } public override string ToString() { return this.personName; } } public struct Example { public static void Main() { Person person1 = new Person("John"); Person person2 = new Person("John"); Console.WriteLine("Calling Equals:"); Console.WriteLine(person1.Equals(person2)); Console.WriteLine("\nCasting to an Object and calling Equals:"); Console.WriteLine(((object) person1).Equals((object) person2)); } } // The example displays the following output: // Calling Equals: // True // // Casting to an Object and calling Equals: // True
// Define a value type that does not override Equals. [<Struct>] type Person(personName: string) = override _.ToString() = personName let person1 = Person "John" let person2 = Person "John" printfn "Calling Equals:" printfn $"{person1.Equals person2}" printfn $"\nCasting to an Object and calling Equals:" printfn $"{(person1 :> obj).Equals(person2 :> obj)}" // The example displays the following output: // Calling Equals: // True // // Casting to an Object and calling Equals: // True
' Define a value type that does not override Equals. Public Structure Person Private personName As String Public Sub New(name As String) Me.personName = name End Sub Public Overrides Function ToString() As String Return Me.personName End Function End Structure Module Example Public Sub Main() Dim p1 As New Person("John") Dim p2 As New Person("John") Console.WriteLine("Calling Equals:") Console.WriteLine(p1.Equals(p2)) Console.WriteLine() Console.WriteLine("Casting to an Object and calling Equals:") Console.WriteLine(CObj(p1).Equals(p2)) End Sub End Module ' The example displays the following output: ' Calling Equals: ' True ' ' Casting to an Object and calling Equals: ' True
Object Ponieważ klasa jest klasą bazową dla wszystkich typów w .NET Framework, Object.Equals(Object) metoda zapewnia domyślne porównanie równości dla wszystkich innych typów. Jednak typy często przesłaniają metodę Equals w celu zaimplementowania równości wartości. Aby uzyskać więcej informacji, zobacz sekcje Uwagi dla osób wywołujących i Uwagi dotyczące dziedziczy.
Uwagi dotyczące środowisko wykonawcze systemu Windows
Po wywołaniu Equals(Object) przeciążenia metody w klasie w środowisko wykonawcze systemu Windows zapewnia ono domyślne zachowanie dla klas, które nie zastępują Equals(Object)klasy . Jest to część wsparcia zapewnianego przez .NET Framework dla środowisko wykonawcze systemu Windows (zobacz .NET Framework pomoc techniczna dla aplikacji ze sklepu Windows i środowisko wykonawcze systemu Windows). Klasy w środowisko wykonawcze systemu Windows nie dziedziczą Object, a obecnie nie implementują Equals(Object) metody . Jednak wydają się ToStringmieć metody , Equals(Object)i GetHashCode podczas ich używania w kodzie C# lub Visual Basic, a .NET Framework zapewnia domyślne zachowanie dla tych metod.
Uwaga
środowisko wykonawcze systemu Windows klasy napisane w języku C# lub Visual Basic mogą zastąpić Equals(Object) przeciążenie metody.
Uwagi dotyczące wywoływania
Klasy pochodne często przesłaniają metodę Object.Equals(Object) w celu zaimplementowania równości wartości. Ponadto typy często zapewniają dodatkowe silnie typizowane przeciążenie Equals
metody, zazwyczaj przez implementację interfejsu IEquatable<T> . Podczas wywoływania Equals
metody w celu przetestowania równości należy wiedzieć, czy bieżące wystąpienie zastępuje Object.Equals i rozumie, jak jest rozwiązywane określone wywołanie Equals
metody. W przeciwnym razie możesz wykonać test równości, który różni się od zamierzonego, a metoda może zwrócić nieoczekiwaną wartość.
Poniższy przykład stanowi ilustrację. Tworzy wystąpienie trzech StringBuilder obiektów z identycznymi ciągami, a następnie wykonuje cztery wywołania metod Equals
. Pierwsze wywołanie metody zwraca wartość true
, a pozostałe trzy zwraca wartość false
.
using System;
using System.Text;
public class Example
{
public static void Main()
{
StringBuilder sb1 = new StringBuilder("building a string...");
StringBuilder sb2 = new StringBuilder("building a string...");
Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2));
Console.WriteLine("((Object) sb1).Equals(sb2): {0}",
((Object) sb1).Equals(sb2));
Console.WriteLine("Object.Equals(sb1, sb2): {0}",
Object.Equals(sb1, sb2));
Object sb3 = new StringBuilder("building a string...");
Console.WriteLine("\nsb3.Equals(sb2): {0}", sb3.Equals(sb2));
}
}
// The example displays the following output:
// sb1.Equals(sb2): True
// ((Object) sb1).Equals(sb2): False
// Object.Equals(sb1, sb2): False
//
// sb3.Equals(sb2): False
open System
open System.Text
let sb1 = StringBuilder "building a string..."
let sb2 = StringBuilder "building a string..."
printfn $"sb1.Equals(sb2): {sb1.Equals sb2}"
printfn $"((Object) sb1).Equals(sb2): {(sb1 :> obj).Equals sb2}"
printfn $"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}"
let sb3 = StringBuilder "building a string..."
printfn $"\nsb3.Equals(sb2): {sb3.Equals sb2}"
// The example displays the following output:
// sb1.Equals(sb2): True
// ((Object) sb1).Equals(sb2): False
// Object.Equals(sb1, sb2): False
//
// sb3.Equals(sb2): False
Imports System.Text
Module Example
Public Sub Main()
Dim sb1 As New StringBuilder("building a string...")
Dim sb2 As New StringBuilder("building a string...")
Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2))
Console.WriteLine("CObj(sb1).Equals(sb2): {0}",
CObj(sb1).Equals(sb2))
Console.WriteLine("Object.Equals(sb1, sb2): {0}",
Object.Equals(sb1, sb2))
Console.WriteLine()
Dim sb3 As Object = New StringBuilder("building a string...")
Console.WriteLine("sb3.Equals(sb2): {0}", sb3.Equals(sb2))
End Sub
End Module
' The example displays the following output:
' sb1.Equals(sb2): True
' CObj(sb1).Equals(sb2): False
' Object.Equals(sb1, sb2): False
'
' sb3.Equals(sb2): False
W pierwszym przypadku wywoływane jest silnie typizowane StringBuilder.Equals(StringBuilder) przeciążenie metody, które testuje równość wartości. Ponieważ ciągi przypisane do dwóch StringBuilder obiektów są równe, metoda zwraca wartość true
. StringBuilder Jednak nie zastępuje Object.Equals(Object)elementu . W związku z tym, gdy StringBuilder obiekt jest rzutowany do Objectobiektu , gdy StringBuilder wystąpienie jest przypisane do zmiennej typu Object, a gdy Object.Equals(Object, Object) metoda jest przekazywana dwa StringBuilder obiekty, wywoływana jest metoda domyślna Object.Equals(Object) . Ponieważ StringBuilder jest to typ odwołania, jest to równoważne przekazaniu dwóch StringBuilder obiektów do ReferenceEquals metody . Mimo że wszystkie trzy StringBuilder obiekty zawierają identyczne ciągi, odwołują się do trzech odrębnych obiektów. W rezultacie te trzy wywołania metody zwracają metodę false
.
Bieżący obiekt można porównać z innym obiektem pod kątem równości odwołań, wywołując metodę ReferenceEquals . W Visual Basic można również użyć słowa kluczowego is
(na przykład If Me Is otherObject Then ...
).
Uwagi dotyczące obiektów dziedziczących
Podczas definiowania własnego typu typ ten dziedziczy funkcjonalność zdefiniowaną przez metodę Equals
jej typu podstawowego. W poniższej tabeli przedstawiono domyślną implementację Equals
metody dla głównych kategorii typów w .NET Framework.
Kategoria typów | Równość zdefiniowana przez | Komentarze |
---|---|---|
Klasa pochodna bezpośrednio z Object | Object.Equals(Object) | Równość odwołań; równoważne wywołaniu metody Object.ReferenceEquals. |
Struktura | ValueType.Equals | Równość wartości; porównanie bajtów bajtów lub porównanie pól według pól przy użyciu odbicia. |
Wyliczenie | Enum.Equals | Wartości muszą mieć ten sam typ wyliczenia i tę samą wartość bazowa. |
Delegat | MulticastDelegate.Equals | Delegaci muszą mieć ten sam typ z identycznymi listami wywołań. |
Interfejs | Object.Equals(Object) | Równość odwołań. |
W przypadku typu wartości należy zawsze przesłonić Equalsmetodę , ponieważ testy równości, które opierają się na odbiciu, oferują niską wydajność. Można również zastąpić domyślną implementację dla typów referencyjnych Equals , aby przetestować równość wartości zamiast równości odwołań i zdefiniować dokładne znaczenie równości wartości. Takie implementacje zwracane Equals true
, jeśli dwa obiekty mają taką samą wartość, nawet jeśli nie są tym samym wystąpieniem. Implementator typu decyduje o tym, co stanowi wartość obiektu, ale zazwyczaj są to niektóre lub wszystkie dane przechowywane w zmiennych wystąpienia obiektu. Na przykład wartość String obiektu jest oparta na znakach ciągu. String.Equals(Object) Metoda zastępuje Object.Equals(Object) metodę zwracaną true
dla wszystkich dwóch wystąpień ciągów, które zawierają te same znaki w tej samej kolejności.
W poniższym przykładzie pokazano, jak przesłonić metodę do testowania pod kątem Object.Equals(Object) równości wartości. Zastępuje metodę Equals Person
klasy . Jeśli Person
zaakceptowano implementację równości klas bazowych, dwa Person
obiekty byłyby równe tylko wtedy, gdy odwoływały się do pojedynczego obiektu. Jednak w tym przypadku dwa Person
obiekty są równe, jeśli mają tę samą wartość dla Person.Id
właściwości.
public class Person
{
private string idNumber;
private string personName;
public Person(string name, string id)
{
this.personName = name;
this.idNumber = id;
}
public override bool Equals(Object obj)
{
Person personObj = obj as Person;
if (personObj == null)
return false;
else
return idNumber.Equals(personObj.idNumber);
}
public override int GetHashCode()
{
return this.idNumber.GetHashCode();
}
}
public class Example
{
public static void Main()
{
Person p1 = new Person("John", "63412895");
Person p2 = new Person("Jack", "63412895");
Console.WriteLine(p1.Equals(p2));
Console.WriteLine(Object.Equals(p1, p2));
}
}
// The example displays the following output:
// True
// True
open System
type Person(name, id) =
member _.Name = name
member _.Id = id
override _.Equals(obj) =
match obj with
| :? Person as personObj ->
id.Equals personObj.Id
| _ ->
false
override _.GetHashCode() =
id.GetHashCode()
let p1 = Person("John", "63412895")
let p2 = Person("Jack", "63412895")
printfn $"{p1.Equals p2}"
printfn $"{Object.Equals(p1, p2)}"
// The example displays the following output:
// True
// True
Public Class Person
Private idNumber As String
Private personName As String
Public Sub New(name As String, id As String)
Me.personName = name
Me.idNumber = id
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim personObj As Person = TryCast(obj, Person)
If personObj Is Nothing Then
Return False
Else
Return idNumber.Equals(personObj.idNumber)
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.idNumber.GetHashCode()
End Function
End Class
Module Example
Public Sub Main()
Dim p1 As New Person("John", "63412895")
Dim p2 As New Person("Jack", "63412895")
Console.WriteLine(p1.Equals(p2))
Console.WriteLine(Object.Equals(p1, p2))
End Sub
End Module
' The example displays the following output:
' True
' True
Oprócz zastępowania Equalsmożna zaimplementować IEquatable<T> interfejs w celu zapewnienia silnie typizowanego testu równości.
Następujące instrukcje muszą być prawdziwe dla wszystkich implementacji Equals(Object) metody . Na liście , x``y
i z
reprezentują odwołania do obiektów, które nie mają wartości null.
x.Equals(x)
metoda zwraca wartośćtrue
.x.Equals(y)
Zwraca tę samą wartość coy.Equals(x)
.x.Equals(y)
metoda zwraca wartośćtrue
, jeśli wartość ix
y
ma wartośćNaN
.Jeśli
(x.Equals(y) && y.Equals(z))
funkcja zwracatrue
wartość ,x.Equals(z)
zwraca wartośćtrue
.Kolejne wywołania zwracają
x.Equals(y)
tę samą wartość, o ile obiekty, do którychx
odwołuje się obiekt iy
nie są modyfikowane.x.Equals(null)
metoda zwraca wartośćfalse
.
Implementacje programu Equals nie mogą zgłaszać wyjątków; zawsze powinny zwracać wartość. Jeśli na przykład to , metoda powinna zwrócić false
wartość zamiast zgłaszać element ArgumentNullException.Equals null``obj
Podczas zastępowania Equals(Object)programu postępuj zgodnie z następującymi wytycznymi:
Typy implementujące IComparable muszą zastąpić Equals(Object).
Typy, które zastępują Equals(Object) , również muszą zastąpić ; w przeciwnym razie tabele GetHashCodeskrótów mogą nie działać poprawnie.
Należy rozważyć zaimplementowanie interfejsu IEquatable<T> w celu obsługi silnie typiowanych testów pod kątem równości. Implementacja IEquatable<T>.Equals powinna zwracać wyniki zgodne z .Equals
Jeśli język programowania obsługuje przeciążenie operatorów i przeciążasz operator równości dla danego typu, należy również zastąpić metodę Equals(Object) , aby zwrócić ten sam wynik co operator równości. Pomaga to zagwarantować, że kod biblioteki klas używający Equals (na przykład ArrayList i Hashtable) zachowuje się w sposób zgodny ze sposobem, w jaki operator równości jest używany przez kod aplikacji.
Wytyczne dla typów odwołania
Poniższe wskazówki dotyczą zastępowania Equals(Object) typu odwołania:
Rozważ zastąpienie Equals , jeśli semantyka typu jest oparta na fakcie, że typ reprezentuje niektóre wartości.
Większość typów odwołań nie może przeciążać operatora równości, nawet jeśli zastąpią Equalswartość . Jeśli jednak implementujesz typ odwołania, który ma mieć semantykę wartości, taką jak typ liczby zespolonej, musisz zastąpić operator równości.
Nie należy zastępować Equals modyfikowalnego typu odwołania. Jest to spowodowane tym, że zastąpienie Equals wymaga również zastąpienia GetHashCode metody, jak opisano w poprzedniej sekcji. Oznacza to, że kod skrótu wystąpienia modyfikowalnego typu odwołania może ulec zmianie w okresie istnienia, co może spowodować utratę obiektu w tabeli skrótów.
Wytyczne dla typów wartości
Poniższe wskazówki dotyczą zastępowania Equals(Object) typu wartości:
Jeśli definiujesz typ wartości, który zawiera co najmniej jedno pole, którego wartości są typami referencyjnymi, należy zastąpić wartość Equals(Object). Implementacja Equals(Object) dostarczana przez program ValueType wykonuje porównanie bajtów bajtów dla typów wartości, których pola są wszystkimi typami wartości, ale używa odbicia do porównania typów wartości według pól, których pola obejmują typy referencyjne.
Jeśli przesłonisz Equals i język programowania obsługuje przeciążenie operatorów, musisz przeciążyć operator równości.
Należy zaimplementować IEquatable<T> interfejs. Wywoływanie metody silnie typizowanej IEquatable<T>.Equals pozwala uniknąć tworzenia pola argumentu
obj
.
Zobacz też
Dotyczy
Equals(Object, Object)
Określa, czy określone wystąpienia obiektów są traktowane jako równe.
public:
static bool Equals(System::Object ^ objA, System::Object ^ objB);
public static bool Equals (object objA, object objB);
public static bool Equals (object? objA, object? objB);
static member Equals : obj * obj -> bool
Public Shared Function Equals (objA As Object, objB As Object) As Boolean
Parametry
- objA
- Object
Pierwszy obiekt do porównania.
- objB
- Object
Drugi obiekt do porównania.
Zwraca
true
jeśli obiekty są uważane za równe; w przeciwnym razie , false
. Jeśli obie objA
wartości i objB
mają wartość null, metoda zwraca wartość true
.
Przykłady
Poniższy przykład ilustruje metodę Equals(Object, Object) i porównuje ją z ReferenceEquals metodą .
using System;
public class Example
{
public static void Main()
{
Dog m1 = new Dog("Alaskan Malamute");
Dog m2 = new Dog("Alaskan Malamute");
Dog g1 = new Dog("Great Pyrenees");
Dog g2 = g1;
Dog d1 = new Dog("Dalmation");
Dog n1 = null;
Dog n2 = null;
Console.WriteLine("null = null: {0}", Object.Equals(n1, n2));
Console.WriteLine("null Reference Equals null: {0}\n", Object.ReferenceEquals(n1, n2));
Console.WriteLine("{0} = {1}: {2}", g1, g2, Object.Equals(g1, g2));
Console.WriteLine("{0} Reference Equals {1}: {2}\n", g1, g2, Object.ReferenceEquals(g1, g2));
Console.WriteLine("{0} = {1}: {2}", m1, m2, Object.Equals(m1, m2));
Console.WriteLine("{0} Reference Equals {1}: {2}\n", m1, m2, Object.ReferenceEquals(m1, m2));
Console.WriteLine("{0} = {1}: {2}", m1, d1, Object.Equals(m1, d1));
Console.WriteLine("{0} Reference Equals {1}: {2}", m1, d1, Object.ReferenceEquals(m1, d1));
}
}
public class Dog
{
// Public field.
public string Breed;
// Class constructor.
public Dog(string dogBreed)
{
this.Breed = dogBreed;
}
public override bool Equals(Object obj)
{
if (obj == null || !(obj is Dog))
return false;
else
return this.Breed == ((Dog) obj).Breed;
}
public override int GetHashCode()
{
return this.Breed.GetHashCode();
}
public override string ToString()
{
return this.Breed;
}
}
// The example displays the following output:
// null = null: True
// null Reference Equals null: True
//
// Great Pyrenees = Great Pyrenees: True
// Great Pyrenees Reference Equals Great Pyrenees: True
//
// Alaskan Malamute = Alaskan Malamute: True
// Alaskan Malamute Reference Equals Alaskan Malamute: False
//
// Alaskan Malamute = Dalmation: False
// Alaskan Malamute Reference Equals Dalmation: False
open System
// Class constructor
type Dog(dogBreed) =
// Public property.
member _.Breed = dogBreed
override this.Equals(obj) =
match obj with
| :? Dog as dog when dog.Breed = this.Breed -> true
| _ -> false
override _.GetHashCode() =
dogBreed.GetHashCode()
override _.ToString() =
dogBreed
let m1 = Dog "Alaskan Malamute"
let m2 = Dog "Alaskan Malamute"
let g1 = Dog "Great Pyrenees"
let g2 = g1
let d1 = Dog "Dalmation"
let n1 = Unchecked.defaultof<Dog>
let n2 = Unchecked.defaultof<Dog>
printfn $"null = null: {Object.Equals(n1, n2)}"
printfn $"null Reference Equals null: {Object.ReferenceEquals(n1, n2)}\n"
printfn $"{g1} = {g2}: {Object.Equals(g1, g2)}"
printfn $"{g1} Reference Equals {g2}: {Object.ReferenceEquals(g1, g2)}\n"
printfn $"{m1} = {m2}: {Object.Equals(m1, m2)}"
printfn $"{m1} Reference Equals {m2}: {Object.ReferenceEquals(m1, m2)}\n"
printfn $"{m1} = {d1}: {Object.Equals(m1, d1)}"
printfn $"{m1} Reference Equals {d1}: {Object.ReferenceEquals(m1, d1)}"
// The example displays the following output:
// null = null: True
// null Reference Equals null: True
//
// Great Pyrenees = Great Pyrenees: True
// Great Pyrenees Reference Equals Great Pyrenees: True
//
// Alaskan Malamute = Alaskan Malamute: True
// Alaskan Malamute Reference Equals Alaskan Malamute: False
//
// Alaskan Malamute = Dalmation: False
// Alaskan Malamute Reference Equals Dalmation: False
Module Example
Public Sub Main()
Dim m1 As New Dog("Alaskan Malamute")
Dim m2 As New Dog("Alaskan Malamute")
Dim g1 As New Dog("Great Pyrenees")
Dim g2 As Dog = g1
Dim d1 As New Dog("Dalmation")
Dim n1 As Dog = Nothing
Dim n2 As Dog = Nothing
Console.WriteLine("null = null: {0}", Object.Equals(n1, n2))
Console.WriteLine("null Reference Equals null: {0}", Object.ReferenceEquals(n1, n2))
Console.WriteLine()
Console.WriteLine("{0} = {1}: {2}", g1, g2, Object.Equals(g1, g2))
Console.WriteLine("{0} Reference Equals {1}: {2}", g1, g2, Object.ReferenceEquals(g1, g2))
Console.WriteLine()
Console.WriteLine("{0} = {1}: {2}", m1, m2, Object.Equals(m1, m2))
Console.WriteLine("{0} Reference Equals {1}: {2}", m1, m2, Object.ReferenceEquals(m1, m2))
Console.WriteLine()
Console.WriteLine("{0} = {1}: {2}", m1, d1, Object.Equals(m1, d1))
Console.WriteLine("{0} Reference Equals {1}: {2}", m1, d1, Object.ReferenceEquals(m1, d1))
End Sub
End Module
Public Class Dog
' Public field.
Public Breed As String
' Class constructor.
Public Sub New(dogBreed As String)
Me.Breed = dogBreed
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing OrElse Not typeof obj Is Dog Then
Return False
Else
Return Me.Breed = CType(obj, Dog).Breed
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.Breed.GetHashCode()
End Function
Public Overrides Function ToString() As String
Return Me.Breed
End Function
End Class
' The example displays the following output:
' null = null: True
' null Reference Equals null: True
'
' Great Pyrenees = Great Pyrenees: True
' Great Pyrenees Reference Equals Great Pyrenees: True
'
' Alaskan Malamute = Alaskan Malamute: True
' Alaskan Malamute Reference Equals Alaskan Malamute: False
'
' Alaskan Malamute = Dalmation: False
' Alaskan Malamute Reference Equals Dalmation: False
Uwagi
Metoda statyczna Equals(Object, Object) wskazuje, czy dwa obiekty i objA
objB
, są równe. Umożliwia również testowanie obiektów, których wartość ma wartość null dla równości. Porównuje objA
objB
i pod kątem równości w następujący sposób:
Określa, czy dwa obiekty reprezentują to samo odwołanie do obiektu. Jeśli tak, metoda zwraca
true
wartość . Ten test jest odpowiednikiem wywoływania ReferenceEquals metody . Ponadto, jeśli obieobjA
wartości iobjB
mają wartość null, metoda zwracatrue
wartość .Określa, czy ma wartość
objA
null, czyobjB
też ma wartość null. Jeśli tak, zwraca wartośćfalse
.Jeśli dwa obiekty nie reprezentują tego samego odwołania do obiektu i żadna z nich nie ma wartości null, wywołuje metodę
objA
.Equals
(objB
) i zwraca wynik. Oznacza to, że jeśliobjA
zastąpi metodę Object.Equals(Object) , to zastąpienie jest wywoływane.