CaseInsensitiveComparer Classe

Definição

Compara dois objetos quanto à equivalência, ignorando maiúsculas e minúsculas em cadeias de caracteres.Compares two objects for equivalence, ignoring the case of strings.

public ref class CaseInsensitiveComparer : System::Collections::IComparer
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class CaseInsensitiveComparer : System.Collections.IComparer
type CaseInsensitiveComparer = class
    interface IComparer
Public Class CaseInsensitiveComparer
Implements IComparer
Herança
CaseInsensitiveComparer
Atributos
Implementações

Exemplos

O exemplo de código a seguir cria uma tabela de hash que diferencia maiúsculas de minúsculas e uma tabela de hash que não diferencia maiúsculas de minúsculas e demonstra a diferença em seu comportamento, mesmo que ambas contenham os mesmos elementos.The following code example creates a case-sensitive hash table and a case-insensitive hash table and demonstrates the difference in their behavior, even if both contain the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
int main()
{
   
   // Create a Hashtable using the default hash code provider and the default comparer.
   Hashtable^ myHT1 = gcnew 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 = gcnew Hashtable( gcnew CaseInsensitiveHashCodeProvider,gcnew 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 = gcnew 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 = gcnew CultureInfo( "tr-TR" );
   Hashtable^ myHT4 = gcnew Hashtable( gcnew CaseInsensitiveHashCodeProvider( myCul ),gcnew 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

*/
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

Comentários

CaseInsensitiveComparerimplementa a IComparer interface que dá suporte a comparações que não diferenciam maiúsculas de IHashCodeProvider minúsculas em cadeias de caracteres, assim como CaseInsensitiveHashCodeProvider implementa a interface que suporta comparações que não diferenciam maiúsculasCaseInsensitiveComparer implements the IComparer interface supporting case-insensitive comparisons on strings, just as CaseInsensitiveHashCodeProvider implements the IHashCodeProvider interface supporting case-insensitive comparisons on strings.

Importante

Não recomendamos que você use a CaseInsensitiveComparer classe para o novo desenvolvimento.We don't recommend that you use the CaseInsensitiveComparer class for new development. Em vez disso, recomendamos que você System.StringComparer use o objeto retornado StringComparer.CurrentCultureIgnoreCasepela StringComparer.InvariantCultureIgnoreCasePropriedade, StringComparer.OrdinalIgnoreCase ou.Instead, we recommend that you use the System.StringComparer object returned by the StringComparer.CurrentCultureIgnoreCase, StringComparer.InvariantCultureIgnoreCase, or StringComparer.OrdinalIgnoreCase property.

A Comparer classe é a implementação padrão da interface IComparer e executa comparações de cadeias de caracteres que diferenciam maiúsculas de minúsculas.The Comparer class is the default implementation of the IComparer interface and performs case-sensitive string comparisons.

Os objetos usados como chaves por um Hashtable são necessários para substituir o Object.GetHashCode método (ou a IHashCodeProvider interface) e o Object.Equals método (ou a IComparer interface).The objects used as keys by a Hashtable are required to override the Object.GetHashCode method (or the IHashCodeProvider interface) and the Object.Equals method (or the IComparer interface). A implementação de ambos os métodos ou interfaces deve lidar com a diferenciação de maiúsculas e minúsculas da mesma forma; caso contrário, Hashtable o pode se comportar incorretamente.The implementation of both methods or interfaces must handle case sensitivity the same way; otherwise, the Hashtable might behave incorrectly. Por exemplo, ao criar um Hashtable, você deve usar essa classe com a CaseInsensitiveHashCodeProvider classe ou qualquer implementação que não diferencia IHashCodeProvider maiúsculas de minúsculas.For example, when creating a Hashtable, you must use this class with the CaseInsensitiveHashCodeProvider class or any case-insensitive IHashCodeProvider implementation.

As comparações de cadeia de caracteres podem ter resultados diferentes dependendo da cultura.String comparisons might have different results depending on the culture. Para obter mais informações sobre comparações específicas de cultura, System.Globalization consulte o namespace e a globalização e a localização.For more information on culture-specific comparisons, see the System.Globalization namespace and Globalization and Localization.

Construtores

CaseInsensitiveComparer()

Inicializa uma nova instância da classe CaseInsensitiveComparer usando o CurrentCulture do thread atual.Initializes a new instance of the CaseInsensitiveComparer class using the CurrentCulture of the current thread.

CaseInsensitiveComparer(CultureInfo)

Inicializa uma nova instância da classe CaseInsensitiveComparer usando o CultureInfo especificado.Initializes a new instance of the CaseInsensitiveComparer class using the specified CultureInfo.

Propriedades

Default

Obtém uma instância de CaseInsensitiveComparer que está associada ao CurrentCulture do thread atual e que está sempre disponível.Gets an instance of CaseInsensitiveComparer that is associated with the CurrentCulture of the current thread and that is always available.

DefaultInvariant

Obtém uma instância de CaseInsensitiveComparer que está associada ao InvariantCulture e que está sempre disponível.Gets an instance of CaseInsensitiveComparer that is associated with InvariantCulture and that is always available.

Métodos

Compare(Object, Object)

Executa uma comparação que não diferencia maiúsculas de minúsculas de dois objetos do mesmo tipo e retorna um valor que indica se um é menor que, igual a ou maior que o outro.Performs a case-insensitive comparison of two objects of the same type and returns a value indicating whether one is less than, equal to, or greater than the other.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Aplica-se a

Veja também