Comparer<T>.IComparer.Compare(Object, Object) メソッド

定義

2 つのオブジェクトを比較し、一方が他方より小さいか、等しいか、または大きいかを示す値を返します。

 virtual int System.Collections.IComparer.Compare(System::Object ^ x, System::Object ^ y) = System::Collections::IComparer::Compare;
int IComparer.Compare(object x, object y);
abstract member System.Collections.IComparer.Compare : obj * obj -> int
override this.System.Collections.IComparer.Compare : obj * obj -> int
Function Compare (x As Object, y As Object) As Integer Implements IComparer.Compare

パラメーター

x
Object

比較する最初のオブジェクト。

y
Object

比較する 2 番目のオブジェクト。

返品

次の表に示すように、 xyの相対値を示す符号付き整数。

価値 意味
0 未満 xy未満です。
ゼロ xyと等しくなります。
0 より大きい xy より大きい。

実装

例外

x または y が型 Tにキャストできない型です。

-または-

x yは、IComparable<T>ジェネリック インターフェイスまたは IComparable インターフェイスを実装しません。

次の例は、 IComparer.Compare メソッドを使用して 2 つのオブジェクトを比較する方法を示しています。 この例は、 Comparer<T> クラスに提供されるより大きな例の一部です。


// This explicit interface implementation
// compares first by the length.
// Returns -1 because the length of BoxA
// is less than the length of BoxB.
BoxLengthFirst LengthFirst = new BoxLengthFirst();

Comparer<Box> bc = (Comparer<Box>) LengthFirst;

Box BoxA = new Box(2, 6, 8);
Box BoxB = new Box(10, 12, 14);
int x = LengthFirst.Compare(BoxA, BoxB);
Console.WriteLine();
Console.WriteLine(x.ToString());

// This explicit interface implementation
// compares first by the length.
// Returns -1 because the length of BoxA
// is less than the length of BoxB.
let LengthFirst = BoxLengthFirst()

let bc = LengthFirst :> Comparer<Box>

let BoxA = Box(2, 6, 8)
let BoxB = Box(10, 12, 14)
let x = LengthFirst.Compare(BoxA, BoxB)
printfn $"\n{x}"

' This explicit interface implementation
' compares first by the length.
' Returns -1 because the length of BoxA
' is less than the length of BoxB.
Dim LengthFirst As New BoxLengthFirst()

Dim bc As Comparer(Of Box) = CType(LengthFirst, Comparer(Of Box))

Dim BoxA As New Box(2, 6, 8)
Dim BoxB As New Box(10, 12, 14)
Dim x As Integer = LengthFirst.Compare(BoxA, BoxB)
Console.WriteLine()
Console.WriteLine(x.ToString())

注釈

このメソッドは Compare(T, T) メソッドのラッパーであるため、 obj は現在のインスタンスのジェネリック引数 T で指定された型にキャストする必要があります。 Tにキャストできない場合は、ArgumentExceptionがスローされます。

nullを任意の参照型と比較することは許可されており、例外は生成されません。 並べ替える場合、 null は他のどのオブジェクトよりも小さいと見なされます。

注意 (呼び出し元)

Compare(T, T)Equals(T, T) は、カルチャの感度と大文字と小文字の区別の点で動作が異なります。

文字列比較の場合、 StringComparer クラスは Comparer<String>よりも推奨されます。 StringComparer クラスのプロパティは、カルチャの区別と大文字と小文字の区別の異なる組み合わせで文字列比較を実行する定義済みのインスタンスを返します。 大文字と小文字の区別とカルチャの区別は、同じ StringComparer インスタンスのメンバー間で一貫しています。

カルチャ固有の比較の詳細については、 System.Globalization 名前空間と グローバリゼーションとローカライズに関するページを参照してください。

適用対象

こちらもご覧ください