CaseInsensitiveComparer Класс

Определение

Сравнивает два объекта для эквивалентности, игнорируя регистр строк.

public ref class CaseInsensitiveComparer : System::Collections::IComparer
public class CaseInsensitiveComparer : System.Collections.IComparer
[System.Serializable]
public class CaseInsensitiveComparer : System.Collections.IComparer
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class CaseInsensitiveComparer : System.Collections.IComparer
type CaseInsensitiveComparer = class
    interface IComparer
[<System.Serializable>]
type CaseInsensitiveComparer = class
    interface IComparer
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type CaseInsensitiveComparer = class
    interface IComparer
Public Class CaseInsensitiveComparer
Implements IComparer
Наследование
CaseInsensitiveComparer
Атрибуты
Реализации

Примеры

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

using System;
using System.Collections;
using System.Globalization;

public class SamplesHashtable  {

   public static void Main()  {

      // Create a Hashtable using the default hash code provider and the default comparer.
      Hashtable myHT1 = new Hashtable();
      myHT1.Add("FIRST", "Hello");
      myHT1.Add("SECOND", "World");
      myHT1.Add("THIRD", "!");

      // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
      // based on the culture of the current thread.
      Hashtable myHT2 = new Hashtable( new CaseInsensitiveHashCodeProvider(), new CaseInsensitiveComparer() );
      myHT2.Add("FIRST", "Hello");
      myHT2.Add("SECOND", "World");
      myHT2.Add("THIRD", "!");

      // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
      // based on the InvariantCulture.
      Hashtable myHT3 = new Hashtable( CaseInsensitiveHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant );
      myHT3.Add("FIRST", "Hello");
      myHT3.Add("SECOND", "World");
      myHT3.Add("THIRD", "!");

      // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
      // based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
      CultureInfo myCul = new CultureInfo( "tr-TR" );
      Hashtable myHT4 = new Hashtable( new CaseInsensitiveHashCodeProvider( myCul ), new CaseInsensitiveComparer( myCul ) );
      myHT4.Add("FIRST", "Hello");
      myHT4.Add("SECOND", "World");
      myHT4.Add("THIRD", "!");

      // Search for a key in each hashtable.
      Console.WriteLine( "first is in myHT1: {0}", myHT1.ContainsKey( "first" ) );
      Console.WriteLine( "first is in myHT2: {0}", myHT2.ContainsKey( "first" ) );
      Console.WriteLine( "first is in myHT3: {0}", myHT3.ContainsKey( "first" ) );
      Console.WriteLine( "first is in myHT4: {0}", myHT4.ContainsKey( "first" ) );
   }
}


/*
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: True
first is in myHT4: False

*/
Imports System.Collections
Imports System.Globalization

Public Class SamplesHashtable

   Public Shared Sub Main()

      ' Create a Hashtable using the default hash code provider and the default comparer.
      Dim myHT1 As New Hashtable()
      myHT1.Add("FIRST", "Hello")
      myHT1.Add("SECOND", "World")
      myHT1.Add("THIRD", "!")

      ' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
      ' based on the culture of the current thread.
      Dim myHT2 As New Hashtable(New CaseInsensitiveHashCodeProvider(), New CaseInsensitiveComparer())
      myHT2.Add("FIRST", "Hello")
      myHT2.Add("SECOND", "World")
      myHT2.Add("THIRD", "!")

      ' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
      ' based on the InvariantCulture.
      Dim myHT3 As New Hashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant)
      myHT3.Add("FIRST", "Hello")
      myHT3.Add("SECOND", "World")
      myHT3.Add("THIRD", "!")

      ' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
      ' based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT4 As New Hashtable(New CaseInsensitiveHashCodeProvider(myCul), New CaseInsensitiveComparer(myCul))
      myHT4.Add("FIRST", "Hello")
      myHT4.Add("SECOND", "World")
      myHT4.Add("THIRD", "!")

      ' Search for a key in each hashtable.
      Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
      Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
      Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))
      Console.WriteLine("first is in myHT4: {0}", myHT4.ContainsKey("first"))

   End Sub

End Class


'This code produces the following output.  Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: True
'first is in myHT4: False

Комментарии

CaseInsensitiveComparer IComparer реализует интерфейс, поддерживающий нечувствительные сравнения регистра в строках, так же, как CaseInsensitiveHashCodeProvider и интерфейсIHashCodeProvider, поддерживающий нечувствительные сравнения регистра в строках.

Important

Мы не рекомендуем использовать CaseInsensitiveComparer класс для новой разработки. Вместо этого рекомендуется использовать System.StringComparer объект, возвращаемый свойством , StringComparer.CurrentCultureIgnoreCaseили StringComparer.InvariantCultureIgnoreCase свойствомStringComparer.OrdinalIgnoreCase.

Класс Comparer является реализацией IComparer интерфейса по умолчанию и выполняет сравнения строк с учетом регистра.

Объекты, используемые в качестве ключей, Hashtable необходимы для переопределения Object.GetHashCode метода (или IHashCodeProvider интерфейса) и Object.Equals метода (или IComparer интерфейса). Реализация обоих методов или интерфейсов должна обрабатывать чувствительность регистра одинаково; Hashtable в противном случае поведение может быть неправильно. Например, при создании Hashtableкласса необходимо использовать этот класс с классом CaseInsensitiveHashCodeProvider или любой реализацией без учета IHashCodeProvider регистра.

Сравнение строк может иметь разные результаты в зависимости от языка и региональных параметров. Дополнительные сведения о сравнениях, относящихся к языку и региональным параметрам, см. в System.Globalization пространстве имен и глобализации и локализации.

Конструкторы

Имя Описание
CaseInsensitiveComparer()

Инициализирует новый экземпляр CaseInsensitiveComparer класса с помощью CurrentCulture текущего потока.

CaseInsensitiveComparer(CultureInfo)

Инициализирует новый экземпляр класса с помощью указанного CaseInsensitiveComparerCultureInfo.

Свойства

Имя Описание
Default

Возвращает экземпляр CaseInsensitiveComparer , связанный с CurrentCulture текущим потоком, который всегда доступен.

DefaultInvariant

Возвращает экземпляр, связанный CaseInsensitiveComparer с InvariantCulture ним, и он всегда доступен.

Методы

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

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

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

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

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