Comparer.Compare(Object, Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
對兩個同類型物件進行大小寫區分比較,並回傳一個值,表示其中一個小於、等於或大於另一個。
public:
virtual int Compare(System::Object ^ a, System::Object ^ b);
public int Compare(object a, object b);
public int Compare(object? a, object? b);
abstract member Compare : obj * obj -> int
override this.Compare : obj * obj -> int
Public Function Compare (a As Object, b As Object) As Integer
參數
- a
- Object
第一個比較的對象。
- b
- Object
第二個比較物件。
傳回
一個有符號整數,表示 和 a的b相對值,如下表所示。
| 價值 | 意義 |
|---|---|
| 低於零 |
a 小於 b。
|
| 零 |
a 等於 b.
|
| 大於零 |
a 大於 b。
|
實作
例外狀況
範例
以下程式碼範例展示了如何 Compare 根據與 相關 Comparer文化而回傳不同的值。
using System;
using System.Collections;
using System.Globalization;
public class SamplesComparer {
public static void Main() {
// Creates the strings to compare.
String str1 = "llegar";
String str2 = "lugar";
Console.WriteLine( "Comparing \"{0}\" and \"{1}\" ...", str1, str2 );
// Uses the DefaultInvariant Comparer.
Console.WriteLine( " Invariant Comparer: {0}", Comparer.DefaultInvariant.Compare( str1, str2 ) );
// Uses the Comparer based on the culture "es-ES" (Spanish - Spain, international sort).
Comparer myCompIntl = new Comparer( new CultureInfo( "es-ES", false ) );
Console.WriteLine( " International Sort: {0}", myCompIntl.Compare( str1, str2 ) );
// Uses the Comparer based on the culture identifier 0x040A (Spanish - Spain, traditional sort).
Comparer myCompTrad = new Comparer( new CultureInfo( 0x040A, false ) );
Console.WriteLine( " Traditional Sort : {0}", myCompTrad.Compare( str1, str2 ) );
}
}
/*
This code produces the following output.
Comparing "llegar" and "lugar" ...
Invariant Comparer: -1
International Sort: -1
Traditional Sort : 1
*/
Imports System.Collections
Imports System.Globalization
Public Class SamplesComparer
Public Shared Sub Main()
' Creates the strings to compare.
Dim str1 As [String] = "llegar"
Dim str2 As [String] = "lugar"
Console.WriteLine("Comparing ""{0}"" and ""{1}"" ...", str1, str2)
' Uses the DefaultInvariant Comparer.
Console.WriteLine(" Invariant Comparer: {0}", Comparer.DefaultInvariant.Compare(str1, str2))
' Uses the Comparer based on the culture "es-ES" (Spanish - Spain, international sort).
Dim myCompIntl As New Comparer(New CultureInfo("es-ES", False))
Console.WriteLine(" International Sort: {0}", myCompIntl.Compare(str1, str2))
' Uses the Comparer based on the culture identifier 0x040A (Spanish - Spain, traditional sort).
Dim myCompTrad As New Comparer(New CultureInfo(&H40A, False))
Console.WriteLine(" Traditional Sort : {0}", myCompTrad.Compare(str1, str2))
End Sub
End Class
'This code produces the following output.
'
'Comparing "llegar" and "lugar" ...
' Invariant Comparer: -1
' International Sort: -1
' Traditional Sort : 1
備註
若 a 實現 IComparable,則 a。
CompareTo
b() 返回;否則,若 b 實現 IComparable,則 的b否定結果。
CompareTo
a()被退回。
允許與任意型別比較 null ,且在使用 IComparable時不會產生例外。 排序時, null 被視為比其他任何物件都小。
弦比對可能因文化不同而有不同的結果。 欲了解更多文化特定比較資訊,請參閱 System.Globalization 命名空間及 全球化與在地化。