# Comparer<T>.IComparer.Compare(Object, Object) Method

## Definition

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

#### Returns

Int32

Value 含义Meaning

Zero `x` 等于 `y``x` equals `y`.

#### Exceptions

`x``y` 所属的类型无法被强制转换为类型 `T``x` or `y` is of a type that cannot be cast to type `T`.

-或--or- `x``y` 不实现 IComparable<T> 泛型接口或 IComparable 接口。`x` and `y` do not implement either the IComparable<T> generic interface or the IComparable interface.

## Examples

``````
// 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.
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())
``````

## Notes to Callers

Compare(T, T)System.Collections.Generic.EqualityComparer`1.Equals(\`0,\`0) 在区分区域性和区分大小写方面具有不同的行为。 Compare(T, T) and System.Collections.Generic.EqualityComparer`1.Equals(\`0,\`0) behave differently in terms of culture-sensitivity and case-sensitivity. 对于字符串比较，建议将 StringComparer`<string>上的比较器`For string comparisons, the StringComparer class is recommended over `Comparer<String>`. StringComparer 类的属性返回预定义实例，这些实例可执行具有不同的区域性敏感性和区分大小写的组合的字符串比较。Properties of the StringComparer class return predefined instances that perform string comparisons with different combinations of culture-sensitivity and case-sensitivity. 同一个 StringComparer 实例的成员之间的区分大小写和区分大小写。The case-sensitivity and culture-sensitivity are consistent among the members of the same StringComparer instance. 有关区域性特定比较的详细信息，请参阅 System.Globalization 命名空间以及[全球化和本地化](/dotnet/standard/globalization-localization/)。For more information on culture-specific comparisons, see the System.Globalization namespace and [Globalization and Localization](/dotnet/standard/globalization-localization/).