Comparer<T>.IComparer.Compare(Object, Object) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
比较两个对象并返回一个值,该值指示一个对象是小于、等于还是大于另一个对象。
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
要比较的第二个对象。
返回
一个有符号整数,指示其相对值 x , y如下表所示。
| 值 | 意义 |
|---|---|
| 小于零 |
x 小于 y。
|
| 零 |
x 等于 y。
|
| 大于零 |
x 大于 y。
|
实现
例外
示例
以下示例演示如何使用 IComparer.Compare 该方法比较两个对象。 此示例是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 命名空间 和全球化和本地化。