Object.Equals Methode
Definition
Stellt fest, ob zwei Objektinstanzen gleich sind.Determines whether two object instances are equal.
Überlädt
Equals(Object) |
Bestimmt, ob das angegebene Objekt mit dem aktuellen Objekt identisch ist.Determines whether the specified object is equal to the current object. |
Equals(Object, Object) |
Stellt fest, ob die angegebenen Objektinstanzen als gleich betrachtet werden.Determines whether the specified object instances are considered equal. |
Equals(Object)
Bestimmt, ob das angegebene Objekt mit dem aktuellen Objekt identisch ist.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
Parameter
- obj
- Object
Das Objekt, das mit dem aktuellen Objekt verglichen werden soll.The object to compare with the current object.
Gibt zurück
true
, wenn das angegebene Objekt und das aktuelle Objekt gleich sind, andernfalls false
.true
if the specified object is equal to the current object; otherwise, false
.
Beispiele
Das folgende Beispiel zeigt eine Point
-Klasse, die die Equals -Methode überschreibt, um Wert Gleichheit bereitzustellen, und eine Point3D
Klasse, die von abgeleitet wird 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
. Da Point
überschreibt, Object.Equals(Object) um auf Wert Gleichheit zu testen, wird die- Object.Equals(Object) Methode nicht aufgerufen.Because Point
overrides Object.Equals(Object) to test for value equality, the Object.Equals(Object) method is not called. Allerdings wird von Point3D.Equals
aufgerufen, Point.Equals
da Point
Object.Equals(Object) in eine Weise implementiert, die Wert Gleichheit bereitstellt.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
Die Point.Equals
-Methode überprüft, ob das obj
-Argument nicht null ist und verweist auf eine Instanz des gleichen Typs wie dieses Objekt.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. Wenn eine der beiden Überprüfungen fehlschlägt, gibt die Methode zurück false
.If either check fails, the method returns false
.
Die- Point.Equals
Methode ruft die- GetType Methode auf, um zu bestimmen, ob die Lauf Zeit Typen der beiden-Objekte identisch sind.The Point.Equals
method calls the GetType method to determine whether the run-time types of the two objects are identical. Wenn die Methode obj is Point
in c# oder in Visual Basic eine Überprüfung des Formulars verwendet TryCast(obj, Point)
hat, würde die Überprüfung in Fällen zurückgegeben, in true
denen eine Instanz einer obj
abgeleiteten Klasse von ist Point
, obwohl obj
und die aktuelle Instanz nicht denselben Lauf Zeittyp aufweisen.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. Nachdem überprüft wurde, ob beide Objekte denselben Typ aufweisen, wandelt die Methode obj
in den Typ um Point
und gibt das Ergebnis des Vergleichs der Instanzfelder der beiden Objekte zurück.Having verified that both objects are of the same type, the method casts obj
to type Point
and returns the result of comparing the instance fields of the two objects.
In Point3D.Equals
wird die geerbte Point.Equals
Methode, die überschreibt Object.Equals(Object) , aufgerufen, bevor etwas anderes ausgeführt wird.In Point3D.Equals
, the inherited Point.Equals
method, which overrides Object.Equals(Object), is invoked before anything else is done. Da Point3D
eine versiegelte Klasse ( NotInheritable
in Visual Basic) ist, ist eine Prüfung in der Form obj is Point
in c# oder TryCast(obj, Point)
in Visual Basic ausreichend, um sicherzustellen, dass obj
ein- Point3D
Objekt ist.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. Wenn es sich um ein Point3D
-Objekt handelt, wird es in ein Point
-Objekt umgewandelt und an die Basisklassen Implementierung von übermittelt Equals .If it is a Point3D
object, it is cast to a Point
object and passed to the base class implementation of Equals. Nur wenn die geerbte Point.Equals
Methode zurückgibt, true
vergleicht die Methode die z
Instanzfelder, die in der abgeleiteten Klasse eingeführt wurden.Only when the inherited Point.Equals
method returns true
does the method compare the z
instance fields introduced in the derived class.
Im folgenden Beispiel wird eine Rectangle
Klasse definiert, die intern ein Rechteck als zwei- Point
Objekte implementiert.The following example defines a Rectangle
class that internally implements a rectangle as two Point
objects. Die- Rectangle
Klasse überschreibt auch Object.Equals(Object) , um Wert Gleichheit bereitzustellen.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
Einige Sprachen wie c# und Visual Basic Support Operator überladen.Some languages such as C# and Visual Basic support operator overloading. Wenn ein Typ den Gleichheits Operator überlädt, muss er auch die-Methode überschreiben, Equals(Object) um die gleiche Funktionalität bereitzustellen.When a type overloads the equality operator, it must also override the Equals(Object) method to provide the same functionality. Dies wird in der Regel erreicht, indem die- Equals(Object) Methode in Bezug auf den überladenen Gleichheits Operator geschrieben wird, wie im folgenden Beispiel gezeigt.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
Da Complex
ein Werttyp ist, kann er nicht von abgeleitet werden.Because Complex
is a value type, it cannot be derived from. Daher muss die Außerkraftsetzungs Equals(Object) Methode nicht aufrufen, GetType um den genauen Lauf Zeittyp der einzelnen Objekte zu bestimmen. stattdessen kann der- is
Operator in c# oder der- TypeOf
Operator in Visual Basic verwendet werden, um den Typ des Parameters zu überprüfen 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.
Hinweise
Der Typ des Vergleichs zwischen der aktuellen Instanz und dem- obj
Parameter hängt davon ab, ob es sich bei der aktuellen Instanz um einen Verweistyp oder einen Werttyp handelt.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.
Wenn es sich bei der aktuellen Instanz um einen Verweistyp handelt, Equals(Object) testet die Methode auf Verweis Gleichheit, und ein Rückruf der- Equals(Object) Methode entspricht einem-aufrufstyp 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. Verweis Gleichheit bedeutet, dass die zu vergleichenden Objektvariablen auf das gleiche Objekt verweisen.Reference equality means that the object variables that are compared refer to the same object. Das folgende Beispiel veranschaulicht das Ergebnis eines solchen Vergleichs.The following example illustrates the result of such a comparison. Es definiert eine
Person
-Klasse, bei der es sich um einen Verweistyp handelt, und ruft den-Person
Klassenkonstruktor auf, um zwei neuePerson
-Objekte, und, zu instanziieren,person1a
person2
die denselben Wert aufweisen.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. Sie weist auchperson1a
einer anderen Objektvariablen () zuperson1b
.It also assignsperson1a
to another object variable,person1b
. Wie die Ausgabe des Beispiels zeigt,person1a
sind undperson1b
gleich, da Sie auf dasselbe Objekt verweisen.As the output from the example shows,person1a
andperson1b
are equal because they reference the same object.person1a
Und sind jedochperson2
nicht gleich, obwohl Sie denselben Wert aufweisen.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
Wenn die aktuelle Instanz ein Werttyp ist, Equals(Object) testet die Methode auf Wert Gleichheit.If the current instance is a value type, the Equals(Object) method tests for value equality. Wert Gleichheit bedeutet Folgendes:Value equality means the following:
Die beiden Objekte weisen denselben Typ auf.The two objects are of the same type. Wie im folgenden Beispiel gezeigt, ist ein- Byte Objekt mit dem Wert 12 nicht mit einem Int32 Objekt identisch, das den Wert 12 aufweist, da die beiden-Objekte unterschiedliche Lauf Zeit Typen aufweisen.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
Die Werte der öffentlichen und privaten Felder der beiden Objekte sind gleich.The values of the public and private fields of the two objects are equal. Im folgenden Beispiel wird auf Wert Gleichheit getestet.The following example tests for value equality. Er definiert eine
Person
-Struktur, bei der es sich um einen Werttyp handelt, und ruft den-Person
Klassenkonstruktor auf, um zwei neuePerson
-Objekte,person1
und, zu instanziierenperson2
.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. Wie die Ausgabe des Beispiels zeigt, sind die beiden Objektvariablen auf verschiedene Objekte verweisen,person1
undperson2
sind gleich, da Sie den gleichen Wert für das privatepersonName
Feld aufweisen.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
Da die- Object Klasse die Basisklasse für alle Typen in der .NET Framework ist, Object.Equals(Object) stellt die-Methode den Standard Gleichheits Vergleich für alle anderen Typen bereit.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. Typen überschreiben jedoch oft die- Equals Methode, um Wert Gleichheit zu implementieren.However, types often override the Equals method to implement value equality. Weitere Informationen finden Sie in den Abschnitten "Hinweise zu Aufrufern und Notizen für Vererbung".For more information, see the Notes for Callers and Notes for Inheritors sections.
Hinweise zum Windows-RuntimeWindows RuntimeNotes for the Windows-RuntimeWindows Runtime
Wenn Sie die- Equals(Object) Methoden Überladung für eine Klasse im aufrufen Windows-RuntimeWindows Runtime , stellt Sie das Standardverhalten für Klassen bereit, die nicht überschreiben Equals(Object) .When you call the Equals(Object) method overload on a class in the Windows-RuntimeWindows Runtime, it provides the default behavior for classes that don't override Equals(Object). Dies ist ein Teil der Unterstützung, die der .NET Framework für bietet Windows-RuntimeWindows Runtime (siehe .NET Framework-Unterstützung für Windows Store-Apps und Windows-Runtime).This is part of the support that the .NET Framework provides for the Windows-RuntimeWindows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Klassen in der Windows-RuntimeWindows Runtime erben nicht Object und implementieren derzeit keine- Equals(Object) Methode.Classes in the Windows-RuntimeWindows Runtime don't inherit Object, and currently don't implement an Equals(Object) method. Allerdings scheinen Sie die ToString Methoden, und zu haben, Equals(Object) Wenn Sie GetHashCode Sie im c#-oder Visual Basic-Code verwenden, und die .NET Framework stellt das Standardverhalten für diese Methoden bereit.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.
Hinweis
Windows-RuntimeWindows Runtime Klassen, die in c# oder Visual Basic geschrieben sind, können die- Equals(Object) Methoden Überladung überschreiben.classes that are written in C# or Visual Basic can override the Equals(Object) method overload.
Hinweise für AufruferNotes for Callers
Abgeleitete Klassen überschreiben die- Object.Equals(Object) Methode häufig, um Wert Gleichheit zu implementieren.Derived classes frequently override the Object.Equals(Object) method to implement value equality. Außerdem stellen Typen häufig eine zusätzliche stark typisierte Überladung für die- Equals
Methode bereit, in der Regel durch Implementieren der- IEquatable<T> Schnittstelle.In addition, types also frequently provide an additional strongly typed overload to the Equals
method, typically by implementing the IEquatable<T> interface. Wenn Sie die- Equals
Methode zum Testen auf Gleichheit aufzurufen, sollten Sie wissen, ob die aktuelle Instanz überschreibt Object.Equals und versteht, wie ein bestimmter aufzurufende Equals
Methode aufgelöst wird.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. Andernfalls können Sie einen Test auf Gleichheit durchführen, der sich von der vorgesehenen Methode unterscheidet, und die Methode gibt möglicherweise einen unerwarteten Wert zurück.Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value.
Dies wird im folgenden Beispiel veranschaulicht.The following example provides an illustration. Es instanziiert drei StringBuilder -Objekte mit identischen Zeichen folgen und führt dann vier Aufrufe von- Equals
Methoden aus.It instantiates three StringBuilder objects with identical strings, and then makes four calls to Equals
methods. Der erste Methoden Rückruf gibt zurück true
, und die restlichen drei zurückgeben false
.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
Im ersten Fall wird die stark typisierte StringBuilder.Equals(StringBuilder) Methoden Überladung, die auf Wert Gleichheit testet, aufgerufen.In the first case, the strongly typed StringBuilder.Equals(StringBuilder) method overload, which tests for value equality, is called. Da die den zwei-Objekten zugewiesenen Zeichen folgen StringBuilder gleich sind, gibt die Methode zurück true
.Because the strings assigned to the two StringBuilder objects are equal, the method returns true
. Allerdings wird von StringBuilder nicht überschrieben Object.Equals(Object) .However, StringBuilder does not override Object.Equals(Object). Aus diesem Grund wird beim Umwandeln des StringBuilder Objekts in ein Object -Objekt, wenn eine- StringBuilder Instanz einer Variablen vom Typ zugewiesen ist Object , und bei Object.Equals(Object, Object) Übergabe der Methode mit zwei StringBuilder Objekten die-Standard Object.Equals(Object) Methode aufgerufen.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. Da StringBuilder ein Verweistyp ist, entspricht dies dem übergeben der beiden- StringBuilder Objekte an die- ReferenceEquals Methode.Because StringBuilder is a reference type, this is equivalent to passing the two StringBuilder objects to the ReferenceEquals method. Obwohl alle drei StringBuilder Objekte identische Zeichen folgen enthalten, verweisen Sie auf drei unterschiedliche Objekte.Although all three StringBuilder objects contain identical strings, they refer to three distinct objects. Folglich geben diese drei Methodenaufrufe zurück false
.As a result, these three method calls return false
.
Sie können das aktuelle-Objekt für Verweis Gleichheit mit einem anderen Objekt vergleichen, indem Sie die- ReferenceEquals Methode aufrufen.You can compare the current object to another object for reference equality by calling the ReferenceEquals method. In Visual Basic können Sie auch das- is
Schlüsselwort verwenden (z If Me Is otherObject Then ...
. b.).In Visual Basic, you can also use the is
keyword (for example, If Me Is otherObject Then ...
).
Hinweise für VererberNotes for Inheritors
Wenn Sie einen eigenen Typ definieren, erbt dieser Typ die Funktionalität, die von der- Equals
Methode seines Basistyps definiert wird.When you define your own type, that type inherits the functionality defined by the Equals
method of its base type. In der folgenden Tabelle ist die Standard Implementierung der- Equals
Methode für die Hauptkategorien von Typen in der .NET Framework aufgeführt.The following table lists the default implementation of the Equals
method for the major categories of types in the .NET Framework.
TypkategorieType category | Gleichheit definiert durchEquality defined by | KommentareComments |
---|---|---|
Direkt von abgeleitete Klasse ObjectClass derived directly from Object | Object.Equals(Object) | Verweis Gleichheit entspricht dem Aufrufen von Object.ReferenceEquals .Reference equality; equivalent to calling Object.ReferenceEquals. |
StrukturStructure | ValueType.Equals | Wert Gleichheit; entweder direkter Byte-für-Byte-Vergleich oder Feld-für-Feld-Vergleich mithilfe von Reflektion.Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection. |
EnumerationEnumeration | Enum.Equals | Werte müssen denselben Enumerationstyp und denselben zugrunde liegenden Wert aufweisen.Values must have the same enumeration type and the same underlying value. |
DelegatDelegate | MulticastDelegate.Equals | Delegaten müssen denselben Typ mit identischen Aufruf Listen aufweisen.Delegates must have the same type with identical invocation lists. |
SchnittstelleInterface | Object.Equals(Object) | Verweis Gleichheit.Reference equality. |
Für einen Werttyp sollten Sie immer überschreiben Equals , da Tests auf Gleichheit, die auf Reflektion basieren, eine schlechte Leistung bieten.For a value type, you should always override Equals, because tests for equality that rely on reflection offer poor performance. Sie können auch die Standard Implementierung von Equals für Verweis Typen überschreiben, um auf Wert Gleichheit anstelle der Verweis Gleichheit zu testen und die genaue Bedeutung von Wert Gleichheit zu definieren.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. Solche Implementierungen von Equals geben zurück true
, wenn die beiden-Objekte denselben Wert aufweisen, auch wenn Sie nicht dieselbe Instanz sind.Such implementations of Equals return true
if the two objects have the same value, even if they are not the same instance. Der Implementierer des Typs entscheidet, was den Wert eines Objekts ausmacht, aber es handelt sich in der Regel um einige oder alle Daten, die in den Instanzvariablen des-Objekts gespeichert werden.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. Beispielsweise basiert der Wert eines- String Objekts auf den Zeichen der Zeichenfolge. die-Methode String.Equals(Object) überschreibt die- Object.Equals(Object) Methode, um true
für alle zwei Zeichen folgen Instanzen zurückzugeben, die die gleichen Zeichen in derselben Reihenfolge enthalten.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.
Im folgenden Beispiel wird gezeigt, wie die- Object.Equals(Object) Methode überschrieben wird, um auf Wert Gleichheit zu testen.The following example shows how to override the Object.Equals(Object) method to test for value equality. Er überschreibt die- Equals Methode für die- Person
Klasse.It overrides the Equals method for the Person
class. Wenn Person
die Basisklassen Implementierung von Gleichheit akzeptiert wird, sind zwei Person
Objekte nur dann gleich, wenn Sie auf ein einzelnes Objekt verwiesen haben.If Person
accepted its base class implementation of equality, two Person
objects would be equal only if they referenced a single object. In diesem Fall sind jedoch zwei- Person
Objekte gleich, wenn Sie über denselben Wert für die- Person.Id
Eigenschaft verfügen.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
Zusätzlich zum Überschreiben von Equals können Sie die- IEquatable<T> Schnittstelle implementieren, um einen stark typisierten Test auf Gleichheit bereitzustellen.In addition to overriding Equals, you can implement the IEquatable<T> interface to provide a strongly typed test for equality.
Die folgenden-Anweisungen müssen für alle Implementierungen der-Methode den Wert "true" aufweisen Equals(Object) .The following statements must be true for all implementations of the Equals(Object) method. In der Liste x
stellen, y
und z
Objekt Verweise dar, die nicht null sind.In the list, x
, y
, and z
represent object references that are not null.
x.Equals(x)
Gibt zurücktrue
, außer in Fällen, die Gleit Komma Typen einschließen.x.Equals(x)
returnstrue
, except in cases that involve floating-point types. Siehe ISO/IEC/IEEE 60559:2011, Informationstechnologie--Mikroprozessorsysteme--Floating-Point Arithmetik.See ISO/IEC/IEEE 60559:2011, Information technology -- Microprocessor Systems -- Floating-Point arithmetic.x.Equals(y)
gibt denselben Wert zurück wiey.Equals(x)
.x.Equals(y)
returns the same value asy.Equals(x)
.x.Equals(y)
Gibt zurück,true
Wenn sowohlx
als auchy
sindNaN
.x.Equals(y)
returnstrue
if bothx
andy
areNaN
.Wenn
(x.Equals(y) && y.Equals(z))
zurückgibttrue
,x.Equals(z)
gibt zurücktrue
.If(x.Equals(y) && y.Equals(z))
returnstrue
, thenx.Equals(z)
returnstrue
.Aufeinander folgende Aufrufe
x.Equals(y)
von geben denselben Wert zurück, solange die Objekte, auf die von und verwiesen wird,x
y
nicht geändert werden.Successive calls tox.Equals(y)
return the same value as long as the objects referenced byx
andy
are not modified.x.Equals(null)
gibtfalse
zurück.x.Equals(null)
returnsfalse
.
Implementierungen von Equals dürfen keine Ausnahmen auslösen. Sie sollten immer einen Wert zurückgeben.Implementations of Equals must not throw exceptions; they should always return a value. Wenn beispielsweise obj
den Wert null
hat, Equals sollte die Methode zurückgeben, false
anstatt eine auszulösen ArgumentNullException .For example, if obj
is null
, the Equals method should return false
instead of throwing an ArgumentNullException.
Beachten Sie beim Überschreiben folgende Richtlinien Equals(Object) :Follow these guidelines when overriding Equals(Object):
Typen, die implementieren, IComparable müssen überschreiben Equals(Object) .Types that implement IComparable must override Equals(Object).
Typen, die überschreiben, Equals(Object) müssen ebenfalls überschreiben, GetHashCode andernfalls funktionieren Hash Tabellen möglicherweise nicht ordnungsgemäß.Types that override Equals(Object) must also override GetHashCode; otherwise, hash tables might not work correctly.
Sie sollten die- IEquatable<T> Schnittstelle implementieren, um stark typisierte Tests auf Gleichheit zu unterstützen.You should consider implementing the IEquatable<T> interface to support strongly typed tests for equality. Ihre IEquatable<T>.Equals Implementierung sollte Ergebnisse zurückgeben, die mit konsistent sind Equals .Your IEquatable<T>.Equals implementation should return results that are consistent with Equals.
Wenn Ihre Programmiersprache das Überladen von Operatoren unterstützt und Sie den Gleichheits Operator für einen bestimmten Typ überladen, müssen Sie auch die- Equals(Object) Methode überschreiben, um das gleiche Ergebnis wie der Gleichheits Operator zurückzugeben.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. Dadurch wird sichergestellt, dass sich der von verwendete Klassen Bibliotheks Code (z. b. Equals ArrayList und Hashtable ) so verhält, dass er mit der Art und Weise konsistent ist, wie der Gleichheits Operator von Anwendungscode verwendet wird.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.
Richtlinien für ReferenztypenGuidelines for Reference Types
Die folgenden Richtlinien gelten für die Überschreibung Equals(Object) von für einen Verweistyp:The following guidelines apply to overriding Equals(Object) for a reference type:
Überschreiben Sie ggf Equals ., ob die Semantik des Typs auf der Tatsache basiert, dass der Typ einige Werte darstellt.Consider overriding Equals if the semantics of the type are based on the fact that the type represents some value(s).
Die meisten Verweis Typen dürfen den Gleichheits Operator nicht überladen, auch wenn Sie überschreiben Equals .Most reference types must not overload the equality operator, even if they override Equals. Wenn Sie jedoch einen Verweistyp implementieren, der eine Wert Semantik aufweisen soll (z. b. ein komplexer Nummertyp), müssen Sie den Gleichheits Operator überschreiben.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.
Sie sollten nicht Equals für einen änderbaren Referenztyp überschreiben.You should not override Equals on a mutable reference type. Dies liegt daran, Equals dass das Überschreiben von erfordert, dass Sie auch die-Methode überschreiben GetHashCode , wie im vorherigen Abschnitt erläutert wurde.This is because overriding Equals requires that you also override the GetHashCode method, as discussed in the previous section. Dies bedeutet, dass sich der Hashcode einer Instanz eines änderbaren Verweis Typs während seiner Lebensdauer ändern kann, was dazu führen kann, dass das Objekt in einer Hash Tabelle verloren geht.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.
Richtlinien für WerttypenGuidelines for Value Types
Die folgenden Richtlinien gelten für das Überschreiben Equals(Object) für einen Werttyp:The following guidelines apply to overriding Equals(Object) for a value type:
Wenn Sie einen Werttyp definieren, der ein oder mehrere Felder enthält, deren Werte Verweis Typen sind, sollten Sie überschreiben 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). Die Equals(Object) von bereitgestellte-Implementierung ValueType führt einen Byte-für-Byte-Vergleich für Werttypen durch, deren Felder alle Werttypen sind. Sie verwendet jedoch Reflektion, um einen Feld weisen Vergleich von Werttypen auszuführen, deren Felder Verweis Typen enthalten.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.
Wenn Sie Equals überschreiben und die Entwicklungssprache das Überladen von Operatoren unterstützt, müssen Sie den Gleichheits Operator überladen.If you override Equals and your development language supports operator overloading, you must overload the equality operator.
Sie sollten die- IEquatable<T> Schnittstelle implementieren.You should implement the IEquatable<T> interface. Durch Aufrufen der stark typisierten IEquatable<T>.Equals Methode wird das Boxing des
obj
Arguments vermieden.Calling the strongly typed IEquatable<T>.Equals method avoids boxing theobj
argument.
Siehe auch
Gilt für:
Equals(Object, Object)
Stellt fest, ob die angegebenen Objektinstanzen als gleich betrachtet werden.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
Parameter
- objA
- Object
Das erste zu vergleichende Objekt.The first object to compare.
- objB
- Object
Das zweite zu vergleichende Objekt.The second object to compare.
Gibt zurück
true
, wenn die Objekte als gleich betrachtet werden, andernfalls false
.true
if the objects are considered equal; otherwise, false
. Wenn sowohl objA
, als auch objB
NULL sind, gibt diese Methode true
zurück.If both objA
and objB
are null, the method returns true
.
Beispiele
Im folgenden Beispiel wird die Equals(Object, Object) -Methode veranschaulicht und mit der- ReferenceEquals Methode verglichen.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
Hinweise
Die statische- Equals(Object, Object) Methode gibt an, ob zwei-Objekte, objA
und objB
, gleich sind.The static Equals(Object, Object) method indicates whether two objects, objA
and objB
, are equal. Außerdem können Sie Objekte, deren Wert null ist, auf Gleichheit testen.It also enables you to test objects whose value is null for equality. Er vergleicht objA
und objB
auf Gleichheit wie folgt:It compares objA
and objB
for equality as follows:
Es bestimmt, ob die beiden-Objekte denselben Objekt Verweis darstellen.It determines whether the two objects represent the same object reference. Wenn dies der Fall ist, gibt die Methode zurück
true
.If they do, the method returnstrue
. Dieser Test entspricht dem Aufrufen der- ReferenceEquals Methode.This test is equivalent to calling the ReferenceEquals method. Wenn sowohlobjA
als auchobjB
null sind, gibt die Methode zurücktrue
.In addition, if bothobjA
andobjB
are null, the method returnstrue
.Es bestimmt, ob
objA
entwederobjB
oder null ist.It determines whether eitherobjA
orobjB
is null. Wenn dies der Fall ist, wird zurückgegebenfalse
.If so, it returnsfalse
.Wenn die beiden-Objekte nicht denselben Objekt Verweis darstellen und keines von null ist, wird aufgerufen
objA
.Equals
(objB
) und gibt das Ergebnis zurück.If the two objects do not represent the same object reference and neither is null, it callsobjA
.Equals
(objB
) and returns the result. Dies bedeutet, dassobjA
Object.Equals(Object) diese außer Kraft Setzung aufgerufen wird, wenn die-Methode überschreibt.This means that ifobjA
overrides the Object.Equals(Object) method, this override is called.