Поделиться через


CompareInfo.Compare Метод

Определение

Сравнивает две строки.

Перегрузки

Имя Описание
Compare(String, String)

Сравнивает две строки.

Compare(ReadOnlySpan<Char>, ReadOnlySpan<Char>, CompareOptions)

Сравнивает два диапазона символов только для чтения.

Compare(String, String, CompareOptions)

Сравнивает две строки с указанным CompareOptions значением.

Compare(String, Int32, String, Int32)

Сравнивает конечный раздел строки с конечным разделом другой строки.

Compare(String, Int32, String, Int32, CompareOptions)

Сравнивает конечный раздел строки с конечным разделом другой строки с указанным значением CompareOptions .

Compare(String, Int32, Int32, String, Int32, Int32)

Сравнивает раздел одной строки с разделом другой строки.

Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions)

Сравнивает раздел одной строки с разделом другой строки с помощью указанного CompareOptions значения.

Compare(String, String)

Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs

Сравнивает две строки.

public:
 virtual int Compare(System::String ^ string1, System::String ^ string2);
public:
 int Compare(System::String ^ string1, System::String ^ string2);
public virtual int Compare(string string1, string string2);
public int Compare(string? string1, string? string2);
public virtual int Compare(string? string1, string? string2);
abstract member Compare : string * string -> int
override this.Compare : string * string -> int
member this.Compare : string * string -> int
Public Overridable Function Compare (string1 As String, string2 As String) As Integer
Public Function Compare (string1 As String, string2 As String) As Integer

Параметры

string1
String

Первая сравниваемая строка.

string2
String

Вторая сравниваемая строка.

Возвращаемое значение

32-разрядное целое число со знаком, указывающее лексическую связь между двумя сравнениями.

Ценность Состояние
Нуля Две строки равны.
меньше нуля string1 меньше string2.
больше нуля string1 больше string2.

Примеры

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

  • CompareInfo объект, связанный с испанской культурой (Испания) с международной сортировкой
  • CompareInfo объект, связанный с испанской культурой (Испания) с традиционными сортировками
  • CompareInfo объект, связанный с объектом InvariantCulture
// The following code example compares two strings using the different CompareInfo instances:
//    a CompareInfo instance associated with the "Spanish - Spain" culture with international sort,
//    a CompareInfo instance associated with the "Spanish - Spain" culture with traditional sort, and
//    a CompareInfo instance associated with the InvariantCulture.

using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "calle";
      String myStr2 = "calor";

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      CompareInfo myCompIntl = CompareInfo.GetCompareInfo( "es-ES" );

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      CompareInfo myCompTrad = CompareInfo.GetCompareInfo( 0x040A );

      // Uses the CompareInfo property of the InvariantCulture.
      CompareInfo myCompInva = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myCompIntl.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1, myStr2 );
      Console.WriteLine( "   With myCompIntl.Compare: {0}", myCompIntl.Compare( myStr1, myStr2 ) );
      Console.WriteLine( "   With myCompTrad.Compare: {0}", myCompTrad.Compare( myStr1, myStr2 ) );
      Console.WriteLine( "   With myCompInva.Compare: {0}", myCompInva.Compare( myStr1, myStr2 ) );
   }
}


/*
This code produces the following output.

Comparing "calle" and "calor"
   With myCompIntl.Compare: -1
   With myCompTrad.Compare: 1
   With myCompInva.Compare: -1

*/
' The following code example compares two strings using the different CompareInfo instances:
'    a CompareInfo instance associated with the "Spanish - Spain" culture with international sort,
'    a CompareInfo instance associated with the "Spanish - Spain" culture with traditional sort, and
'    a CompareInfo instance associated with the InvariantCulture.

Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "calle"
      Dim myStr2 As [String] = "calor"

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      Dim myCompIntl As CompareInfo = CompareInfo.GetCompareInfo("es-ES")

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      Dim myCompTrad As CompareInfo = CompareInfo.GetCompareInfo(&H40A)

      ' Uses the CompareInfo property of the InvariantCulture.
      Dim myCompInva As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myCompIntl.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1, myStr2)
      Console.WriteLine("   With myCompIntl.Compare: {0}", myCompIntl.Compare(myStr1, myStr2))
      Console.WriteLine("   With myCompTrad.Compare: {0}", myCompTrad.Compare(myStr1, myStr2))
      Console.WriteLine("   With myCompInva.Compare: {0}", myCompInva.Compare(myStr1, myStr2))

   End Sub

End Class


'This code produces the following output.
'
'Comparing "calle" and "calor"
'   With myCompIntl.Compare: -1
'   With myCompTrad.Compare: 1
'   With myCompInva.Compare: -1

В следующем примере показано, как вызвать Compare метод.

using System;
using System.Text;
using System.Globalization;

public sealed class App
{
    static void Main(string[] args)
    {
        String[] sign = new String[] { "<", "=", ">" };

        // The code below demonstrates how strings compare
        // differently for different cultures.
        String s1 = "Coté", s2 = "coté", s3 = "côte";

        // Set sort order of strings for French in France.
        CompareInfo ci = new CultureInfo("fr-FR").CompareInfo;
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID);

        // Display the result using fr-FR Compare of Coté = coté.  	
        Console.WriteLine("fr-FR Compare: {0} {2} {1}",
            s1, s2, sign[ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1]);

        // Display the result using fr-FR Compare of coté > côte.
        Console.WriteLine("fr-FR Compare: {0} {2} {1}",
            s2, s3, sign[ci.Compare(s2, s3, CompareOptions.None) + 1]);

        // Set sort order of strings for Japanese as spoken in Japan.
        ci = new CultureInfo("ja-JP").CompareInfo;
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID);

        // Display the result using ja-JP Compare of coté < côte.
        Console.WriteLine("ja-JP Compare: {0} {2} {1}",
            s2, s3, sign[ci.Compare(s2, s3) + 1]);
    }
}

// This code produces the following output.
//
// The LCID for fr-FR is 1036.
// fr-FR Compare: Coté = coté
// fr-FR Compare: coté > côte
// The LCID for ja-JP is 1041.
// ja-JP Compare: coté < côte
Imports System.Text
Imports System.Globalization

NotInheritable Public Class App
    Shared Sub Main(ByVal args() As String) 
        Dim sign() As String = {"<", "=", ">"}
        
        ' The code below demonstrates how strings compare 
        ' differently for different cultures.
        Dim s1 As String = "Coté"
        Dim s2 As String = "coté"
        Dim s3 As String = "côte"
        
        ' Set sort order of strings for French in France.
        Dim ci As CompareInfo = New CultureInfo("fr-FR").CompareInfo
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID)
        
        ' Display the result using fr-FR Compare of Coté = coté.  	
        Console.WriteLine("fr-FR Compare: {0} {2} {1}", _
                          s1, s2, sign((ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1)))
        
        ' Display the result using fr-FR Compare of coté > côte.
        Console.WriteLine("fr-FR Compare: {0} {2} {1}", _
                          s2, s3, sign((ci.Compare(s2, s3, CompareOptions.None) + 1)))
        
        ' Set sort order of strings for Japanese as spoken in Japan.
        ci = New CultureInfo("ja-JP").CompareInfo
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID)
        
        ' Display the result using ja-JP Compare of coté < côte. 
        Console.WriteLine("ja-JP Compare: {0} {2} {1}", _
                          s2, s3, sign((ci.Compare(s2, s3) + 1)))
    End Sub
End Class

' This code produces the following output.
' 
' The LCID for fr-FR is 1036.
' fr-FR Compare: Coté = coté
' fr-FR Compare: coté > côte
' The LCID for ja-JP is 1041.
' ja-JP Compare: coté < côte

Комментарии

По умолчанию сравнение выполняется с помощью CompareOptions.None. Если решение безопасности зависит от сравнения строк или изменения регистра, следует использовать InvariantCulture свойство, чтобы обеспечить согласованность поведения независимо от параметров языка и региональных параметров операционной системы.

Замечание

По возможности следует вызвать методы сравнения строк, имеющие параметр типа CompareOptions , чтобы указать ожидаемый тип сравнения. В качестве общего правила используйте языковые параметры (с использованием текущего языка и региональных параметров) для сравнения строк, отображаемых в пользовательском интерфейсе, и укажите Ordinal или OrdinalIgnoreCase для безопасных сравнений.

Примечания для тех, кто вызывает этот метод

Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или учитывающего культуру сравнения. Метод Compare(String, String) не учитывает такие символы при выполнении сравнения с учетом языка и региональных параметров. Например, с учетом языка и региональных параметров сравнение "животное" с "ani-mal" (с помощью мягкого дефиса или U+00AD) указывает, что две строки эквивалентны, как показано в следующем примере.

Imports System.Globalization

Module Example
   Public Sub Main()
      Dim ci As CompareInfo = CultureInfo.CurrentCulture.CompareInfo
      Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
      Dim s2 As String = "animal"
      
      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, s2, ci.Compare(s1, s2))
  End Sub
End Module
' The example displays the following output:
'       Comparison of 'ani-mal' and 'animal': 0

Чтобы распознать игнорируемые символы в сравнении строк, вызовите Compare(String, String, CompareOptions) метод и укажите значение OrdinalOrdinalIgnoreCase либо для options параметра.

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

Compare(ReadOnlySpan<Char>, ReadOnlySpan<Char>, CompareOptions)

Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs

Сравнивает два диапазона символов только для чтения.

public int Compare(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, System.Globalization.CompareOptions options = System.Globalization.CompareOptions.None);
member this.Compare : ReadOnlySpan<char> * ReadOnlySpan<char> * System.Globalization.CompareOptions -> int
Public Function Compare (string1 As ReadOnlySpan(Of Char), string2 As ReadOnlySpan(Of Char), Optional options As CompareOptions = System.Globalization.CompareOptions.None) As Integer

Параметры

string1
ReadOnlySpan<Char>

Первый диапазон символов только для чтения для сравнения.

string2
ReadOnlySpan<Char>

Второй диапазон символов только для чтения для сравнения.

options
CompareOptions

Необязательное сочетание значений перечисления, используемых CompareOptions во время сравнения. Значение по умолчанию — None.

Возвращаемое значение

Ноль, если string1 и string2 равны; или отрицательное значение, если string1 сортируется до string2; или положительное значение, если string1 сортируется после string2.

Исключения

options содержит неподдерживаемое сочетание флагов.

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

Compare(String, String, CompareOptions)

Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs

Сравнивает две строки с указанным CompareOptions значением.

public:
 virtual int Compare(System::String ^ string1, System::String ^ string2, System::Globalization::CompareOptions options);
public:
 int Compare(System::String ^ string1, System::String ^ string2, System::Globalization::CompareOptions options);
public virtual int Compare(string string1, string string2, System.Globalization.CompareOptions options);
public int Compare(string? string1, string? string2, System.Globalization.CompareOptions options);
public virtual int Compare(string? string1, string? string2, System.Globalization.CompareOptions options);
abstract member Compare : string * string * System.Globalization.CompareOptions -> int
override this.Compare : string * string * System.Globalization.CompareOptions -> int
member this.Compare : string * string * System.Globalization.CompareOptions -> int
Public Overridable Function Compare (string1 As String, string2 As String, options As CompareOptions) As Integer
Public Function Compare (string1 As String, string2 As String, options As CompareOptions) As Integer

Параметры

string1
String

Первая сравниваемая строка.

string2
String

Вторая сравниваемая строка.

options
CompareOptions

Значение, определяющее, как string1 и string2 следует сравнивать. options— значение Ordinalперечисления или побитовое сочетание одного или нескольких из следующих значений: IgnoreCase, , IgnoreSymbolsIgnoreNonSpace, IgnoreWidthIgnoreKanaType, NumericOrderingи StringSort.

Возвращаемое значение

32-разрядное целое число со знаком, указывающее лексическую связь между двумя сравнениями.

Ценность Состояние
Нуля Две строки равны.
меньше нуля string1 меньше string2.
больше нуля string1 больше string2.

Исключения

options содержит недопустимое CompareOptions значение.

Примеры

В следующем примере сравниваются две строки с различными CompareOptions параметрами.

using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "My Uncle Bill's clients";
      String myStr2 = "My uncle bills clients";

      // Creates a CompareInfo that uses the InvariantCulture.
      CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myComp.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1, myStr2 );
      Console.WriteLine( "   With no CompareOptions            : {0}", myComp.Compare( myStr1, myStr2 ) );
      Console.WriteLine( "   With None                         : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.None ) );
      Console.WriteLine( "   With Ordinal                      : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.Ordinal ) );
      Console.WriteLine( "   With StringSort                   : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.StringSort ) );
      Console.WriteLine( "   With IgnoreCase                   : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.IgnoreCase ) );
      Console.WriteLine( "   With IgnoreSymbols                : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.IgnoreSymbols ) );
      Console.WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols ) );
   }
}


/*
This code produces the following output.

Comparing "My Uncle Bill's clients" and "My uncle bills clients"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -32
   With StringSort                   : -1
   With IgnoreCase                   : 1
   With IgnoreSymbols                : 1
   With IgnoreCase and IgnoreSymbols : 0

*/
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "My Uncle Bill's clients"
      Dim myStr2 As [String] = "My uncle bills clients"

      ' Creates a CompareInfo that uses the InvariantCulture.
      Dim myComp As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myComp.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1, myStr2)
      Console.WriteLine("   With no CompareOptions            : {0}", myComp.Compare(myStr1, myStr2))
      Console.WriteLine("   With None                         : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.None))
      Console.WriteLine("   With Ordinal                      : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.Ordinal))
      Console.WriteLine("   With StringSort                   : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.StringSort))
      Console.WriteLine("   With IgnoreCase                   : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase))
      Console.WriteLine("   With IgnoreSymbols                : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreSymbols))
      Console.WriteLine("   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase Or CompareOptions.IgnoreSymbols))

   End Sub

End Class


'This code produces the following output.
'
'Comparing "My Uncle Bill's clients" and "My uncle bills clients"
'   With no CompareOptions            : 1
'   With None                         : 1
'   With Ordinal                      : -32
'   With StringSort                   : -1
'   With IgnoreCase                   : 1
'   With IgnoreSymbols                : 1
'   With IgnoreCase and IgnoreSymbols : 0

В следующем примере показано, как вызвать Compare метод.

using System;
using System.Text;
using System.Globalization;

public sealed class App
{
    static void Main(string[] args)
    {
        String[] sign = new String[] { "<", "=", ">" };

        // The code below demonstrates how strings compare
        // differently for different cultures.
        String s1 = "Coté", s2 = "coté", s3 = "côte";

        // Set sort order of strings for French in France.
        CompareInfo ci = new CultureInfo("fr-FR").CompareInfo;
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID);

        // Display the result using fr-FR Compare of Coté = coté.  	
        Console.WriteLine("fr-FR Compare: {0} {2} {1}",
            s1, s2, sign[ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1]);

        // Display the result using fr-FR Compare of coté > côte.
        Console.WriteLine("fr-FR Compare: {0} {2} {1}",
            s2, s3, sign[ci.Compare(s2, s3, CompareOptions.None) + 1]);

        // Set sort order of strings for Japanese as spoken in Japan.
        ci = new CultureInfo("ja-JP").CompareInfo;
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID);

        // Display the result using ja-JP Compare of coté < côte.
        Console.WriteLine("ja-JP Compare: {0} {2} {1}",
            s2, s3, sign[ci.Compare(s2, s3) + 1]);
    }
}

// This code produces the following output.
//
// The LCID for fr-FR is 1036.
// fr-FR Compare: Coté = coté
// fr-FR Compare: coté > côte
// The LCID for ja-JP is 1041.
// ja-JP Compare: coté < côte
Imports System.Text
Imports System.Globalization

NotInheritable Public Class App
    Shared Sub Main(ByVal args() As String) 
        Dim sign() As String = {"<", "=", ">"}
        
        ' The code below demonstrates how strings compare 
        ' differently for different cultures.
        Dim s1 As String = "Coté"
        Dim s2 As String = "coté"
        Dim s3 As String = "côte"
        
        ' Set sort order of strings for French in France.
        Dim ci As CompareInfo = New CultureInfo("fr-FR").CompareInfo
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID)
        
        ' Display the result using fr-FR Compare of Coté = coté.  	
        Console.WriteLine("fr-FR Compare: {0} {2} {1}", _
                          s1, s2, sign((ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1)))
        
        ' Display the result using fr-FR Compare of coté > côte.
        Console.WriteLine("fr-FR Compare: {0} {2} {1}", _
                          s2, s3, sign((ci.Compare(s2, s3, CompareOptions.None) + 1)))
        
        ' Set sort order of strings for Japanese as spoken in Japan.
        ci = New CultureInfo("ja-JP").CompareInfo
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID)
        
        ' Display the result using ja-JP Compare of coté < côte. 
        Console.WriteLine("ja-JP Compare: {0} {2} {1}", _
                          s2, s3, sign((ci.Compare(s2, s3) + 1)))
    End Sub
End Class

' This code produces the following output.
' 
' The LCID for fr-FR is 1036.
' fr-FR Compare: Coté = coté
' fr-FR Compare: coté > côte
' The LCID for ja-JP is 1041.
' ja-JP Compare: coté < côte

Комментарии

Если решение безопасности зависит от сравнения строк или изменения регистра, следует использовать InvariantCulture свойство, чтобы обеспечить согласованность поведения независимо от параметров языка и региональных параметров операционной системы.

Замечание

По возможности следует вызвать методы сравнения строк, имеющие параметр типа CompareOptions , чтобы указать ожидаемый тип сравнения. В качестве общего правила используйте языковые параметры (с использованием текущего языка и региональных параметров) для сравнения строк, отображаемых в пользовательском интерфейсе, и укажите Ordinal или OrdinalIgnoreCase для безопасных сравнений.

Примечания для тех, кто вызывает этот метод

Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или учитывающего культуру сравнения. Метод Compare(String, String, CompareOptions) не учитывает такие символы при выполнении сравнения с учетом языка и региональных параметров. Чтобы распознать игнорируемые символы в сравнении, укажите значение Ordinal или OrdinalIgnoreCase значение параметра options .

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

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

Compare(String, Int32, String, Int32)

Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs

Сравнивает конечный раздел строки с конечным разделом другой строки.

public:
 virtual int Compare(System::String ^ string1, int offset1, System::String ^ string2, int offset2);
public:
 int Compare(System::String ^ string1, int offset1, System::String ^ string2, int offset2);
public virtual int Compare(string string1, int offset1, string string2, int offset2);
public int Compare(string? string1, int offset1, string? string2, int offset2);
public virtual int Compare(string? string1, int offset1, string? string2, int offset2);
abstract member Compare : string * int * string * int -> int
override this.Compare : string * int * string * int -> int
member this.Compare : string * int * string * int -> int
Public Overridable Function Compare (string1 As String, offset1 As Integer, string2 As String, offset2 As Integer) As Integer
Public Function Compare (string1 As String, offset1 As Integer, string2 As String, offset2 As Integer) As Integer

Параметры

string1
String

Первая сравниваемая строка.

offset1
Int32

Отсчитываемый от нуля индекс символа, с string1 которого начинается сравнение.

string2
String

Вторая сравниваемая строка.

offset2
Int32

Отсчитываемый от нуля индекс символа, с string2 которого начинается сравнение.

Возвращаемое значение

32-разрядное целое число со знаком, указывающее лексическую связь между двумя сравнениями.

Ценность Состояние
Нуля Две строки равны.
меньше нуля Указанный раздел string1 меньше указанного string2раздела.
больше нуля Указанный раздел string1 больше указанного string2раздела.

Исключения

offset1 или offset2 меньше нуля.

–или–

offset1 больше или равно числу символов в string1.

–или–

offset2 больше или равно числу символов в string2.

Примеры

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

  • CompareInfo объект, связанный с испанской культурой (Испания) с международной сортировкой

  • CompareInfo объект, связанный с испанской культурой (Испания) с традиционными сортировками

  • CompareInfo объект, связанный с объектом InvariantCulture

using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "calle";
      String myStr2 = "calor";

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      CompareInfo myCompIntl = CompareInfo.GetCompareInfo( "es-ES" );

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      CompareInfo myCompTrad = CompareInfo.GetCompareInfo( 0x040A );

      // Uses the CompareInfo property of the InvariantCulture.
      CompareInfo myCompInva = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myCompIntl.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1.Substring( 2 ), myStr2.Substring( 2 ) );
      Console.WriteLine( "   With myCompIntl.Compare: {0}", myCompIntl.Compare( myStr1, 2, myStr2, 2 ) );
      Console.WriteLine( "   With myCompTrad.Compare: {0}", myCompTrad.Compare( myStr1, 2, myStr2, 2 ) );
      Console.WriteLine( "   With myCompInva.Compare: {0}", myCompInva.Compare( myStr1, 2, myStr2, 2 ) );
   }
}


/*
This code produces the following output.

Comparing "lle" and "lor"
   With myCompIntl.Compare: -1
   With myCompTrad.Compare: 1
   With myCompInva.Compare: -1

*/
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "calle"
      Dim myStr2 As [String] = "calor"

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      Dim myCompIntl As CompareInfo = CompareInfo.GetCompareInfo("es-ES")

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      Dim myCompTrad As CompareInfo = CompareInfo.GetCompareInfo(&H40A)

      ' Uses the CompareInfo property of the InvariantCulture.
      Dim myCompInva As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myCompIntl.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1.Substring(2), myStr2.Substring(2))
      Console.WriteLine("   With myCompIntl.Compare: {0}", myCompIntl.Compare(myStr1, 2, myStr2, 2))
      Console.WriteLine("   With myCompTrad.Compare: {0}", myCompTrad.Compare(myStr1, 2, myStr2, 2))
      Console.WriteLine("   With myCompInva.Compare: {0}", myCompInva.Compare(myStr1, 2, myStr2, 2))

   End Sub

End Class


'This code produces the following output.
'
'Comparing "lle" and "lor"
'   With myCompIntl.Compare: -1
'   With myCompTrad.Compare: 1
'   With myCompInva.Compare: -1

Комментарии

Если решение безопасности зависит от сравнения строк или изменения регистра, следует использовать InvariantCulture свойство, чтобы обеспечить согласованность поведения независимо от параметров языка и региональных параметров операционной системы.

Замечание

По возможности следует вызвать методы сравнения строк, имеющие параметр типа CompareOptions , чтобы указать ожидаемый тип сравнения. В качестве общего правила используйте языковые параметры (с использованием текущего языка и региональных параметров) для сравнения строк, отображаемых в пользовательском интерфейсе, и укажите Ordinal или OrdinalIgnoreCase для безопасных сравнений.

Примечания для тех, кто вызывает этот метод

Наборы символов включают игнорируемые символы. Метод Compare(String, Int32, String, Int32) не учитывает эти символы при выполнении лингвистического или языкового сравнения. Чтобы распознать игнорируемые символы в сравнении, вызовите Compare(String, Int32, String, Int32, CompareOptions) метод и укажите значение Ordinal или OrdinalIgnoreCase для options параметра.

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

Compare(String, Int32, String, Int32, CompareOptions)

Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs

Сравнивает конечный раздел строки с конечным разделом другой строки с указанным значением CompareOptions .

public:
 virtual int Compare(System::String ^ string1, int offset1, System::String ^ string2, int offset2, System::Globalization::CompareOptions options);
public:
 int Compare(System::String ^ string1, int offset1, System::String ^ string2, int offset2, System::Globalization::CompareOptions options);
public virtual int Compare(string string1, int offset1, string string2, int offset2, System.Globalization.CompareOptions options);
public int Compare(string? string1, int offset1, string? string2, int offset2, System.Globalization.CompareOptions options);
public virtual int Compare(string? string1, int offset1, string? string2, int offset2, System.Globalization.CompareOptions options);
abstract member Compare : string * int * string * int * System.Globalization.CompareOptions -> int
override this.Compare : string * int * string * int * System.Globalization.CompareOptions -> int
member this.Compare : string * int * string * int * System.Globalization.CompareOptions -> int
Public Overridable Function Compare (string1 As String, offset1 As Integer, string2 As String, offset2 As Integer, options As CompareOptions) As Integer
Public Function Compare (string1 As String, offset1 As Integer, string2 As String, offset2 As Integer, options As CompareOptions) As Integer

Параметры

string1
String

Первая сравниваемая строка.

offset1
Int32

Отсчитываемый от нуля индекс символа, с string1 которого начинается сравнение.

string2
String

Вторая сравниваемая строка.

offset2
Int32

Отсчитываемый от нуля индекс символа, с string2 которого начинается сравнение.

options
CompareOptions

Значение, определяющее, как string1 и string2 следует сравнивать. options— значение Ordinalперечисления или побитовое сочетание одного или нескольких из следующих значений: IgnoreCase, , IgnoreSymbolsIgnoreNonSpace, IgnoreWidthIgnoreKanaType, NumericOrderingи StringSort.

Возвращаемое значение

32-разрядное целое число со знаком, указывающее лексическую связь между двумя сравнениями.

Ценность Состояние
Нуля Две строки равны.
меньше нуля Указанный раздел string1 меньше указанного string2раздела.
больше нуля Указанный раздел string1 больше указанного string2раздела.

Исключения

offset1 или offset2 меньше нуля.

–или–

offset1 больше или равно числу символов в string1.

–или–

offset2 больше или равно числу символов в string2.

options содержит недопустимое CompareOptions значение.

Примеры

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

using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "My Uncle Bill's clients";
      String myStr2 = "My uncle bills clients";

      // Creates a CompareInfo that uses the InvariantCulture.
      CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myComp.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1.Substring( 10 ), myStr2.Substring( 10 ) );
      Console.WriteLine( "   With no CompareOptions            : {0}", myComp.Compare( myStr1, 10, myStr2, 10 ) );
      Console.WriteLine( "   With None                         : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.None ) );
      Console.WriteLine( "   With Ordinal                      : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.Ordinal ) );
      Console.WriteLine( "   With StringSort                   : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.StringSort ) );
      Console.WriteLine( "   With IgnoreCase                   : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.IgnoreCase ) );
      Console.WriteLine( "   With IgnoreSymbols                : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.IgnoreSymbols ) );
      Console.WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols ) );
   }
}


/*
This code produces the following output.

Comparing "ill's clients" and "ills clients"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -76
   With StringSort                   : -1
   With IgnoreCase                   : 1
   With IgnoreSymbols                : 0
   With IgnoreCase and IgnoreSymbols : 0

*/
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "My Uncle Bill's clients"
      Dim myStr2 As [String] = "My uncle bills clients"

      ' Creates a CompareInfo that uses the InvariantCulture.
      Dim myComp As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myComp.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1.Substring(10), myStr2.Substring(10))
      Console.WriteLine("   With no CompareOptions            : {0}", myComp.Compare(myStr1, 10, myStr2, 10))
      Console.WriteLine("   With None                         : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.None))
      Console.WriteLine("   With Ordinal                      : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.Ordinal))
      Console.WriteLine("   With StringSort                   : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.StringSort))
      Console.WriteLine("   With IgnoreCase                   : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.IgnoreCase))
      Console.WriteLine("   With IgnoreSymbols                : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.IgnoreSymbols))
      Console.WriteLine("   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.IgnoreCase Or CompareOptions.IgnoreSymbols))

   End Sub

End Class


'This code produces the following output.
'
'Comparing "ill's clients" and "ills clients"
'   With no CompareOptions            : 1
'   With None                         : 1
'   With Ordinal                      : -76
'   With StringSort                   : -1
'   With IgnoreCase                   : 1
'   With IgnoreSymbols                : 0
'   With IgnoreCase and IgnoreSymbols : 0

Комментарии

Если решение безопасности зависит от сравнения строк или изменения регистра, следует использовать InvariantCulture свойство, чтобы обеспечить согласованность поведения независимо от параметров языка и региональных параметров операционной системы.

Замечание

По возможности следует вызвать методы сравнения строк, имеющие параметр типа CompareOptions , чтобы указать ожидаемый тип сравнения. В качестве общего правила используйте языковые параметры (с использованием текущего языка и региональных параметров) для сравнения строк, отображаемых в пользовательском интерфейсе, и укажите Ordinal или OrdinalIgnoreCase для безопасных сравнений.

Примечания для тех, кто вызывает этот метод

Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или учитывающего культуру сравнения. Метод Compare(String, Int32, String, Int32, CompareOptions) не учитывает такие символы при выполнении сравнения с учетом языка и региональных параметров. Чтобы распознать игнорируемые символы в сравнении, укажите значение Ordinal или OrdinalIgnoreCase значение параметра options .

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

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

Compare(String, Int32, Int32, String, Int32, Int32)

Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs

Сравнивает раздел одной строки с разделом другой строки.

public:
 virtual int Compare(System::String ^ string1, int offset1, int length1, System::String ^ string2, int offset2, int length2);
public:
 int Compare(System::String ^ string1, int offset1, int length1, System::String ^ string2, int offset2, int length2);
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2);
public int Compare(string? string1, int offset1, int length1, string? string2, int offset2, int length2);
public virtual int Compare(string? string1, int offset1, int length1, string? string2, int offset2, int length2);
abstract member Compare : string * int * int * string * int * int -> int
override this.Compare : string * int * int * string * int * int -> int
member this.Compare : string * int * int * string * int * int -> int
Public Overridable Function Compare (string1 As String, offset1 As Integer, length1 As Integer, string2 As String, offset2 As Integer, length2 As Integer) As Integer
Public Function Compare (string1 As String, offset1 As Integer, length1 As Integer, string2 As String, offset2 As Integer, length2 As Integer) As Integer

Параметры

string1
String

Первая сравниваемая строка.

offset1
Int32

Отсчитываемый от нуля индекс символа, с string1 которого начинается сравнение.

length1
Int32

Число последовательных символов для string1 сравнения.

string2
String

Вторая сравниваемая строка.

offset2
Int32

Отсчитываемый от нуля индекс символа, с string2 которого начинается сравнение.

length2
Int32

Число последовательных символов для string2 сравнения.

Возвращаемое значение

32-разрядное целое число со знаком, указывающее лексическую связь между двумя сравнениями.

Ценность Состояние
Нуля Две строки равны.
меньше нуля Указанный раздел string1 меньше указанного string2раздела.
больше нуля Указанный раздел string1 больше указанного string2раздела.

Исключения

offset1 или length1offset2length2 меньше нуля.

–или–

offset1 больше или равно числу символов в string1.

–или–

offset2 больше или равно числу символов в string2.

–или–

length1 больше числа символов от offset1 конца до конца string1.

–или–

length2 больше числа символов от offset2 конца до конца string2.

Примеры

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

  • CompareInfo объект, связанный с испанской культурой (Испания) с международной сортировкой

  • CompareInfo объект, связанный с испанской культурой (Испания) с традиционными сортировками

  • CompareInfo объект, связанный с объектом InvariantCulture

using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "calle";
      String myStr2 = "calor";

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      CompareInfo myCompIntl = CompareInfo.GetCompareInfo( "es-ES" );

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      CompareInfo myCompTrad = CompareInfo.GetCompareInfo( 0x040A );

      // Uses the CompareInfo property of the InvariantCulture.
      CompareInfo myCompInva = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myCompIntl.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1.Substring( 2, 2 ), myStr2.Substring( 2, 2 ) );
      Console.WriteLine( "   With myCompIntl.Compare: {0}", myCompIntl.Compare( myStr1, 2, 2, myStr2, 2, 2 ) );
      Console.WriteLine( "   With myCompTrad.Compare: {0}", myCompTrad.Compare( myStr1, 2, 2, myStr2, 2, 2 ) );
      Console.WriteLine( "   With myCompInva.Compare: {0}", myCompInva.Compare( myStr1, 2, 2, myStr2, 2, 2 ) );
   }
}


/*
This code produces the following output.

Comparing "ll" and "lo"
   With myCompIntl.Compare: -1
   With myCompTrad.Compare: 1
   With myCompInva.Compare: -1

*/
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "calle"
      Dim myStr2 As [String] = "calor"

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      Dim myCompIntl As CompareInfo = CompareInfo.GetCompareInfo("es-ES")

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      Dim myCompTrad As CompareInfo = CompareInfo.GetCompareInfo(&H40A)

      ' Uses the CompareInfo property of the InvariantCulture.
      Dim myCompInva As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myCompIntl.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1.Substring(2, 2), myStr2.Substring(2, 2))
      Console.WriteLine("   With myCompIntl.Compare: {0}", myCompIntl.Compare(myStr1, 2, 2, myStr2, 2, 2))
      Console.WriteLine("   With myCompTrad.Compare: {0}", myCompTrad.Compare(myStr1, 2, 2, myStr2, 2, 2))
      Console.WriteLine("   With myCompInva.Compare: {0}", myCompInva.Compare(myStr1, 2, 2, myStr2, 2, 2))

   End Sub

End Class


'This code produces the following output.
'
'Comparing "ll" and "lo"
'   With myCompIntl.Compare: -1
'   With myCompTrad.Compare: 1
'   With myCompInva.Compare: -1

Комментарии

Если решение безопасности зависит от сравнения строк или изменения регистра, следует использовать InvariantCulture свойство, чтобы обеспечить согласованность поведения независимо от параметров языка и региональных параметров операционной системы.

Замечание

По возможности следует использовать методы сравнения строк, имеющие параметр типа CompareOptions , чтобы указать ожидаемый тип сравнения. В качестве общего правила используйте языковые параметры (с использованием текущего языка и региональных параметров) для сравнения строк, отображаемых в пользовательском интерфейсе, и укажите Ordinal или OrdinalIgnoreCase для безопасных сравнений.

Примечания для тех, кто вызывает этот метод

Наборы символов включают игнорируемые символы. Метод Compare(String, Int32, Int32, String, Int32, Int32) не учитывает эти символы при выполнении лингвистического или языкового сравнения. Чтобы распознать игнорируемые символы в сравнении, вызовите Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) метод и укажите значение Ordinal или OrdinalIgnoreCase для options параметра.

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

Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions)

Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs
Исходный код:
CompareInfo.cs

Сравнивает раздел одной строки с разделом другой строки с помощью указанного CompareOptions значения.

public:
 virtual int Compare(System::String ^ string1, int offset1, int length1, System::String ^ string2, int offset2, int length2, System::Globalization::CompareOptions options);
public:
 int Compare(System::String ^ string1, int offset1, int length1, System::String ^ string2, int offset2, int length2, System::Globalization::CompareOptions options);
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, System.Globalization.CompareOptions options);
public int Compare(string? string1, int offset1, int length1, string? string2, int offset2, int length2, System.Globalization.CompareOptions options);
public virtual int Compare(string? string1, int offset1, int length1, string? string2, int offset2, int length2, System.Globalization.CompareOptions options);
abstract member Compare : string * int * int * string * int * int * System.Globalization.CompareOptions -> int
override this.Compare : string * int * int * string * int * int * System.Globalization.CompareOptions -> int
member this.Compare : string * int * int * string * int * int * System.Globalization.CompareOptions -> int
Public Overridable Function Compare (string1 As String, offset1 As Integer, length1 As Integer, string2 As String, offset2 As Integer, length2 As Integer, options As CompareOptions) As Integer
Public Function Compare (string1 As String, offset1 As Integer, length1 As Integer, string2 As String, offset2 As Integer, length2 As Integer, options As CompareOptions) As Integer

Параметры

string1
String

Первая сравниваемая строка.

offset1
Int32

Отсчитываемый от нуля индекс символа, с string1 которого начинается сравнение.

length1
Int32

Число последовательных символов для string1 сравнения.

string2
String

Вторая сравниваемая строка.

offset2
Int32

Отсчитываемый от нуля индекс символа, с string2 которого начинается сравнение.

length2
Int32

Число последовательных символов для string2 сравнения.

options
CompareOptions

Значение, определяющее, как string1 и string2 следует сравнивать. options— значение Ordinalперечисления или побитовое сочетание одного или нескольких из следующих значений: IgnoreCase, , IgnoreSymbolsIgnoreNonSpace, IgnoreWidthIgnoreKanaType, NumericOrderingи StringSort.

Возвращаемое значение

32-разрядное целое число со знаком, указывающее лексическую связь между двумя сравнениями.

Ценность Состояние
Нуля Две строки равны.
меньше нуля Указанный раздел string1 меньше указанного string2раздела.
больше нуля Указанный раздел string1 больше указанного string2раздела.

Исключения

offset1 или length1offset2length2 меньше нуля.

–или–

offset1 больше или равно числу символов в string1.

–или–

offset2 больше или равно числу символов в string2.

–или–

length1 больше числа символов от offset1 конца до конца string1.

–или–

length2 больше числа символов от offset2 конца до конца string2.

options содержит недопустимое CompareOptions значение.

Примеры

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

using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "My Uncle Bill's clients";
      String myStr2 = "My uncle bills clients";

      // Creates a CompareInfo that uses the InvariantCulture.
      CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myComp.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1.Substring( 3, 10 ), myStr2.Substring( 3, 10 ) );
      Console.WriteLine( "   With no CompareOptions            : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10 ) );
      Console.WriteLine( "   With None                         : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.None ) );
      Console.WriteLine( "   With Ordinal                      : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.Ordinal ) );
      Console.WriteLine( "   With StringSort                   : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.StringSort ) );
      Console.WriteLine( "   With IgnoreCase                   : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreCase ) );
      Console.WriteLine( "   With IgnoreSymbols                : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreSymbols ) );
      Console.WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols ) );
   }
}


/*
This code produces the following output.

Comparing "Uncle Bill" and "uncle bill"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -32
   With StringSort                   : 1
   With IgnoreCase                   : 0
   With IgnoreSymbols                : 1
   With IgnoreCase and IgnoreSymbols : 0

*/
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "My Uncle Bill's clients"
      Dim myStr2 As [String] = "My uncle bills clients"

      ' Creates a CompareInfo that uses the InvariantCulture.
      Dim myComp As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myComp.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1.Substring(3, 10), myStr2.Substring(3, 10))
      Console.WriteLine("   With no CompareOptions            : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10))
      Console.WriteLine("   With None                         : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.None))
      Console.WriteLine("   With Ordinal                      : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.Ordinal))
      Console.WriteLine("   With StringSort                   : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.StringSort))
      Console.WriteLine("   With IgnoreCase                   : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreCase))
      Console.WriteLine("   With IgnoreSymbols                : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreSymbols))
      Console.WriteLine("   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreCase Or CompareOptions.IgnoreSymbols))

   End Sub

End Class


'This code produces the following output.
'
'Comparing "Uncle Bill" and "uncle bill"
'   With no CompareOptions            : 1
'   With None                         : 1
'   With Ordinal                      : -32
'   With StringSort                   : 1
'   With IgnoreCase                   : 0
'   With IgnoreSymbols                : 1
'   With IgnoreCase and IgnoreSymbols : 0

Комментарии

Если решение безопасности зависит от сравнения строк или изменения регистра, следует использовать InvariantCulture свойство, чтобы обеспечить согласованность поведения независимо от параметров языка и региональных параметров операционной системы.

Замечание

По возможности следует вызвать методы сравнения строк, имеющие параметр типа CompareOptions , чтобы указать ожидаемый тип сравнения. В качестве общего правила используйте языковые параметры (с использованием текущего языка и региональных параметров) для сравнения строк, отображаемых в пользовательском интерфейсе, и укажите Ordinal или OrdinalIgnoreCase для безопасных сравнений.

Примечания для тех, кто вызывает этот метод

Наборы символов включают игнорируемые символы. Метод Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) не учитывает эти символы при выполнении сравнения с учетом языка и региональных параметров. Чтобы распознать игнорируемые символы в сравнении, укажите значение Ordinal или OrdinalIgnoreCase значение параметра options .

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

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