Object.Equals メソッド

定義

2 つのオブジェクト インスタンスが等しいかどうかを判断します。Determines whether two object instances are equal.

オーバーロード

 Equals(Object) 指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。Determines whether the specified object is equal to the current object. Equals(Object, Object) 指定されたインスタンスが等しいかどうかを判断します。Determines whether the specified object instances are considered equal.

Equals(Object)

``````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``

obj
Object

Boolean

例

``````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
``````

メソッドは、 `Point.Equals` `obj` 引数が null でないこと、およびこのオブジェクトと同じ型のインスタンスを参照していることを確認します。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. いずれかのチェックが失敗した場合、メソッドはを返し `false` ます。If either check fails, the method returns `false`.

メソッドは、メソッドを呼び出して、 `Point.Equals` GetType 2 つのオブジェクトの実行時の型が同一かどうかを確認します。The `Point.Equals` method calls the GetType method to determine whether the run-time types of the two objects are identical. メソッドが C# または Visual Basic でフォームのチェックを使用した場合、 `obj is Point` `TryCast(obj, Point)` `true` `obj` `Point` と現在のインスタンスの実行時の型が同じであっても、がの派生クラスのインスタンスである場合、このチェックはを返し `obj` ます。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. 両方のオブジェクトが同じ型であることを確認すると、メソッドは `obj` を型にキャスト `Point` し、2つのオブジェクトのインスタンスフィールドを比較した結果を返します。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.

では、を `Point3D.Equals` `Point.Equals` オーバーライドする継承されたメソッド Object.Equals(Object) が、他の処理が行われる前に呼び出されます。In `Point3D.Equals`, the inherited `Point.Equals` method, which overrides Object.Equals(Object), is invoked before anything else is done. `Point3D`は sealed クラス (Visual Basic) であるため `NotInheritable``obj is Point` `TryCast(obj, Point)` がオブジェクトであることを確認するには、C# または Visual Basic でフォームをチェックインすることをお勧めし `obj` `Point3D` ます。Because `Point3D` is a sealed class (`NotInheritable` in Visual Basic), a check in the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic is adequate to ensure that `obj` is a `Point3D` object. オブジェクトの場合は `Point3D` 、オブジェクトにキャストされ、 `Point` の基本クラスの実装に渡され Equals ます。If it is a `Point3D` object, it is cast to a `Point` object and passed to the base class implementation of Equals. 継承されたメソッドがを返す場合にのみ、 `Point.Equals` `true` メソッドは、 `z` 派生クラスで導入されたインスタンスフィールドを比較します。Only when the inherited `Point.Equals` method returns `true` does the method compare the `z` instance fields introduced in the derived class.

``````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
``````

C# や Visual Basic などの一部の言語では、演算子のオーバーロードがサポートされています。Some languages such as C# and Visual Basic support operator overloading. 型が等値演算子をオーバーロードする場合は、 Equals(Object) 同じ機能を提供するためにメソッドもオーバーライドする必要があります。When a type overloads the equality operator, it must also override the Equals(Object) method to provide the same functionality. 通常、これは、次の Equals(Object) 例に示すように、オーバーロードされた等値演算子の観点からメソッドを記述することで実現されます。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
``````

`Complex`は値型であるため、から派生することはできません。Because `Complex` is a value type, it cannot be derived from. したがって、メソッドへのオーバーライドでは、 Equals(Object) GetType 各オブジェクトの正確な実行時の型を判断するためにを呼び出す必要はありませんが、代わりに `is` C# の演算子または Visual Basic の演算子を使用して、 `TypeOf` パラメーターの型を確認でき `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.

注釈

• 現在のインスタンスが参照型の場合、 Equals(Object) メソッドは参照の等価性をテストし、メソッドの呼び出し Equals(Object) はメソッドの呼び出しに相当し 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. 参照の等価性とは、比較されるオブジェクト変数が同じオブジェクトを参照することを意味します。Reference equality means that the object variables that are compared refer to the same object. 次の例は、このような比較の結果を示しています。The following example illustrates the result of such a comparison. これ `Person` は参照型であるクラスを定義し、クラスコンストラクターを呼び出して、 `Person` 2 つの新しい `Person` オブジェクト `person1a``person2` 、同じ値を持つをインスタンス化します。It defines a `Person` class, which is a reference type, and calls the `Person` class constructor to instantiate two new `Person` objects, `person1a` and `person2`, which have the same value. また `person1a` 、別のオブジェクト変数にも割り当てら `person1b` れます。It also assigns `person1a` to another object variable, `person1b`. この例の出力が示すように、 `person1a``person1b` は同じオブジェクトを参照しているため、と同じです。As the output from the example shows, `person1a` and `person1b` are equal because they reference the same object. ただし、 `person1a` との値が同じであっても、と `person2` は等しくありません。However, `person1a` and `person2` 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
``````
• 現在のインスタンスが値型の場合、 Equals(Object) メソッドは値が等しいかどうかをテストします。If the current instance is a value type, the Equals(Object) method tests for value equality. 値の等価性は、次のことを意味します。Value equality means the following:

• 2つのオブジェクトの型は同じです。The two objects are of the same type. 次の例に示すように、 Byte 値が12のオブジェクトは、値が12のオブジェクトとは Int32 異なります。これは、2つのオブジェクトの実行時の型が異なるためです。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
``````
• 2つのオブジェクトのパブリックフィールドとプライベートフィールドの値が等しい。The values of the public and private fields of the two objects are equal. 次の例では、値が等しいかどうかをテストします。The following example tests for value equality. これは、 `Person` 値型の構造体を定義し、クラスコンストラクターを呼び出して、 `Person` 2 つの新しい `Person` オブジェクト `person1``person2` 、同じ値を持つをインスタンス化します。It defines a `Person` structure, which is a value type, and calls the `Person` class constructor to instantiate two new `Person` objects, `person1` and `person2`, which have the same value. この例の出力はを示していますが、2つのオブジェクト変数は異なるオブジェクトを参照しますが、 `person1` `person2` は、プライベートフィールドの値が同じであるため、同じです `personName`As the output from the example shows, although the two object variables refer to different objects, `person1` and `person2` are equal because they have the same value for the private `personName` 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
``````

クラスは Object .NET Framework 内のすべての型の基底クラスであるため、 Object.Equals(Object) メソッドは、他のすべての型に対して既定の等値比較を提供します。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. ただし、型は多くの場合、 Equals 値の等価性を実装するためにメソッドをオーバーライドします。However, types often override the Equals method to implement value equality. 詳細については、以下を参照してください。の呼び出し元とメモ継承先のセクションです。For more information, see the Notes for Callers and Notes for Inheritors sections.

Windows ランタイムのメモNotes for the Windows Runtime

Windows ランタイムのクラスでメソッドオーバーロードを呼び出すと、 Equals(Object) オーバーライドされないクラスの既定の動作が提供され Equals(Object) ます。When you call the Equals(Object) method overload on a class in the Windows Runtime, it provides the default behavior for classes that don't override Equals(Object). これは、.NET Framework が Windows ランタイムに提供するサポートの一部です (「 Windows ストアアプリと Windows ランタイムの .NET Framework サポート」を参照してください)。This is part of the support that the .NET Framework provides for the Windows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Windows ランタイムのクラスは継承さ Object れず、現在はメソッドを実装していません Equals(Object)Classes in the Windows Runtime don't inherit Object, and currently don't implement an Equals(Object) method. ただし、 ToString Equals(Object) C# または Visual Basic コードで使用するときは、、、およびの各メソッドがあるように見え GetHashCode ます。 .NET Framework は、これらのメソッドの既定の動作を提供します。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.

C# または Visual Basic で記述された Windows ランタイムクラスは、メソッドのオーバーロードをオーバーライドでき Equals(Object) ます。Windows Runtime classes that are written in C# or Visual Basic can override the Equals(Object) method overload.

呼び出し元に関する注意事項Notes for Callers

``````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
``````

メソッドを呼び出すことにより、現在のオブジェクトを別のオブジェクトと比較して、参照の等価性を確認でき ReferenceEquals ます。You can compare the current object to another object for reference equality by calling the ReferenceEquals method. Visual Basic では、キーワード (など) を使用することもでき `is` `If Me Is otherObject Then ...` ます。In Visual Basic, you can also use the `is` keyword (for example, `If Me Is otherObject Then ...`).

継承に関する注意事項Notes for Inheritors

から直接派生したクラス ObjectClass derived directly from Object Object.Equals(Object) 参照の等価性。の呼び出しに相当 Object.ReferenceEquals します。Reference equality; equivalent to calling Object.ReferenceEquals.

インターフェイスInterface Object.Equals(Object) 参照の等価性。Reference equality.

``````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
``````

をオーバーライドするだけでなく Equals 、厳密に IEquatable<T> 型指定されたテストを等価性を提供するインターフェイスを実装することもできます。In addition to overriding Equals, you can implement the IEquatable<T> interface to provide a strongly typed test for equality.

• `x.Equals(x)``true`浮動小数点型が含まれている場合を除き、を返します。`x.Equals(x)` returns `true`, except in cases that involve floating-point types.

• `x.Equals(y)` からは `y.Equals(x)` と同じ値が返されます。`x.Equals(y)` returns the same value as `y.Equals(x)`.

• `x.Equals(y)``true`との両方がである場合は、を返し `x` `y` `NaN` ます。`x.Equals(y)` returns `true` if both `x` and `y` are `NaN`.

• がを返した場合、はを `(x.Equals(y) && y.Equals(z))` `true` `x.Equals(z)` 返し `true` ます。If `(x.Equals(y) && y.Equals(z))` returns `true`, then `x.Equals(z)` returns `true`.

• の連続した呼び出しで `x.Equals(y)` は、およびによって参照されるオブジェクトが変更されない限り、同じ値が返され `x` `y` ます。Successive calls to `x.Equals(y)` return the same value as long as the objects referenced by `x` and `y` are not modified.

• `x.Equals(null)` は、`false` を返します。`x.Equals(null)` returns `false`.

の実装では Equals 、例外をスローすることはできません。常に値を返す必要があります。Implementations of Equals must not throw exceptions; they should always return a value. たとえば、がの場合、 `obj` `null` メソッドはを Equals スローするのではなく、を返す必要があり `false` ArgumentNullException ます。For example, if `obj` is `null`, the Equals method should return `false` instead of throwing an ArgumentNullException.

オーバーライドする場合は、次のガイドラインに従って Equals(Object) ください。Follow these guidelines when overriding Equals(Object):

• を実装する型 IComparable は、をオーバーライドする必要があり Equals(Object) ます。Types that implement IComparable must override Equals(Object).

• オーバーライドする型は、 Equals(Object) もオーバーライドする必要があります。 GetHashCode それ以外の場合、ハッシュテーブルが正しく機能しない可能性があります。Types that override Equals(Object) must also override GetHashCode; otherwise, hash tables might not work correctly.

• IEquatable<T>厳密に型指定されたテストが等しいかどうかをサポートするには、インターフェイスを実装することを検討してください。You should consider implementing the IEquatable<T> interface to support strongly typed tests for equality. IEquatable<T>.Equals実装では、と一致する結果を返す必要があり Equals ます。Your IEquatable<T>.Equals implementation should return results that are consistent with Equals.

• プログラミング言語で演算子のオーバーロードがサポートされていて、特定の型の等値演算子をオーバーロードする場合は、 Equals(Object) 等値演算子と同じ結果を返すようにメソッドをオーバーライドする必要もあります。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. これにより、(やなど) を使用するクラスライブラリコードが、 Equals ArrayList Hashtable アプリケーションコードで等値演算子が使用される方法と一貫性のある方法で動作するようになります。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.

参照型のガイドラインGuidelines for Reference Types

• Equals のセマンティクスが、型がなんらかの値を表しているという事実に基づいているかどうかをオーバーライドすることを検討してください。Consider overriding Equals if the semantics of the type are based on the fact that the type represents some value(s).

• ほとんどの参照型は、をオーバーライドする場合でも、等値演算子をオーバーロードすることはできません EqualsMost reference types must not overload the equality operator, even if they override Equals. ただし、複素数型などの値のセマンティクスを持つ参照型を実装する場合は、等値演算子をオーバーライドする必要があります。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.

• 変更可能 Equals な参照型ではオーバーライドしないでください。You should not override Equals on a mutable reference type. これは、前のセクションで説明したように、をオーバーライドするには、 Equals メソッドもオーバーライドする必要があるためです GetHashCodeThis is because overriding Equals requires that you also override the GetHashCode method, as discussed in the previous section. これは、変更可能な参照型のインスタンスのハッシュコードがその有効期間中に変更される可能性があることを意味します。そのため、ハッシュテーブル内のオブジェクトが失われる可能性があります。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.

値型のガイドラインGuidelines for Value Types

• 値が参照型である1つ以上のフィールドを含む値型を定義する場合は、をオーバーライドする必要があり 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). Equals(Object)によって提供される実装では、 ValueType フィールドがすべての値型である値型のバイト単位の比較を実行しますが、リフレクションを使用して、参照型を含むフィールドを持つ値型のフィールドごとの比較を実行します。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.

• インターフェイスを実装する必要があり IEquatable<T> ます。You should implement the IEquatable<T> interface. 厳密に型指定されたメソッドを呼び出すと IEquatable<T>.Equals 、引数のボックス化が回避さ `obj` れます。Calling the strongly typed IEquatable<T>.Equals method avoids boxing the `obj` argument.

Equals(Object, Object)

``````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``

objA
Object

objB
Object

戻り値

Boolean

オブジェクトが等しいと見なされた場合は `true`。それ以外の場合は `false``true` if the objects are considered equal; otherwise, `false`. `objA``objB` の両方が null の場合、このメソッドは `true` を返します。If both `objA` and `objB` are null, the method returns `true`.

例

``````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 = 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 = Dalmation: False
'       Alaskan Malamute Reference Equals Dalmation: False
``````

注釈

• 2つのオブジェクトが同じオブジェクト参照を表しているかどうかを判断します。It determines whether the two objects represent the same object reference. 指定されている場合、メソッドはを返し `true` ます。If they do, the method returns `true`. このテストは、メソッドを呼び出すことと同じです ReferenceEqualsThis test is equivalent to calling the ReferenceEquals method. さらに、との `objA` 両方 `objB`null の場合、メソッドはを返し `true` ます。In addition, if both `objA` and `objB` are null, the method returns `true`.

• `objA`または `objB`null かどうかを判断します。It determines whether either `objA` or `objB` is null. その場合は、を返し `false` ます。If so, it returns `false`.

• 2つのオブジェクトが同じオブジェクト参照を表しておらず、どちらも null でない場合は、を呼び出し `objA` ます。 `Equals`( `objB` ) とは、結果を返します。If the two objects do not represent the same object reference and neither is null, it calls `objA`.`Equals`(`objB`) and returns the result. これは、が `objA` メソッドをオーバーライドすると Object.Equals(Object) 、このオーバーライドが呼び出されることを意味します。This means that if `objA` overrides the Object.Equals(Object) method, this override is called.