Comparer.Compare(Object, Object) Метод

Определение

Выполняет сравнение двух объектов одного типа с учетом регистра и возвращает значение, указывающее, меньше ли одно, равно или больше, чем другое.

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.

Реализации

Исключения

Ни тот, a ни b и не реализует IComparable интерфейс.

–или–

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 пространстве имен и глобализации и локализации.

Применяется к

См. также раздел