Comparer Comparer Comparer Comparer Class

Definición

Compara dos objetos para ver si son iguales teniendo en cuenta la distinción entre mayúsculas y minúsculas de las cadenas.Compares two objects for equivalence, where string comparisons are case-sensitive.

public ref class Comparer sealed : System::Collections::IComparer, System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class Comparer : System.Collections.IComparer, System.Runtime.Serialization.ISerializable
type Comparer = class
    interface IComparer
    interface ISerializable
Public NotInheritable Class Comparer
Implements IComparer, ISerializable
Herencia
ComparerComparerComparerComparer
Atributos
Implementaciones

Ejemplos

El siguiente ejemplo de código muestra cómo Compare devuelve valores diferentes dependiendo de la referencia cultural asociada con el Comparer.The following code example shows how Compare returns different values depending on the culture associated with the Comparer.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
int 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 = gcnew Comparer( gcnew 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 = gcnew Comparer( gcnew 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

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

End Class 'SamplesComparer


'This code produces the following output.
'
'Comparing "llegar" and "lugar" ...
'   Invariant Comparer: -1
'   International Sort: -1
'   Traditional Sort  : 1

Comentarios

Esta clase es la implementación predeterminada de la IComparer interfaz.This class is the default implementation of the IComparer interface. El CaseInsensitiveComparer clase es la implementación de la IComparer interfaz que realiza comparaciones de cadenas entre mayúsculas y minúsculas.The CaseInsensitiveComparer class is the implementation of the IComparer interface that performs case-insensitive string comparisons. System.Collections.Generic.Comparer<T> es el equivalente genérico de esta clase.System.Collections.Generic.Comparer<T> is the generic equivalent of this class.

Procedimientos de comparación utilizan la Thread.CurrentCulture del actual subproceso a menos que se especifique lo contrario.Comparison procedures use the Thread.CurrentCulture of the current thread unless otherwise specified. Las comparaciones de cadenas podrían tener resultados diferentes en función de la referencia cultural.String comparisons might have different results depending on the culture. Para obtener más información sobre las comparaciones específicas de la referencia cultural, consulte el System.Globalization espacio de nombres y globalización y localización.For more information on culture-specific comparisons, see the System.Globalization namespace and Globalization and Localization.

Constructores

Comparer(CultureInfo) Comparer(CultureInfo) Comparer(CultureInfo) Comparer(CultureInfo)

Inicializa una nueva instancia de la clase Comparer utilizando la clase CultureInfo especificada.Initializes a new instance of the Comparer class using the specified CultureInfo.

Campos

Default Default Default Default

Representa una instancia de Comparer que está asociada a la propiedad CurrentCulture del subproceso actual.Represents an instance of Comparer that is associated with the CurrentCulture of the current thread. Este campo es de solo lectura.This field is read-only.

DefaultInvariant DefaultInvariant DefaultInvariant DefaultInvariant

Representa una instancia de Comparer que está asociada a la propiedad InvariantCulture.Represents an instance of Comparer that is associated with InvariantCulture. Este campo es de solo lectura.This field is read-only.

Métodos

Compare(Object, Object) Compare(Object, Object) Compare(Object, Object) Compare(Object, Object)

Realiza una comparación distinguiendo entre mayúsculas y minúsculas de dos objetos del mismo tipo y devuelve un valor que indica si uno es menor, igual o mayor que el otro.Performs a case-sensitive 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) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Rellena un objeto SerializationInfo con los datos necesarios para la serialización.Populates a SerializationInfo object with the data required for serialization.

GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Se aplica a

Consulte también: