String.IComparable.CompareTo(Object) Método

Definición

Compara esta instancia con un Object especificado e indica si la posición de esta instancia es anterior, posterior o igual que la posición del Objectespecificado en el criterio de ordenación.Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.

 virtual int System.IComparable.CompareTo(System::Object ^ value) = IComparable::CompareTo;
int IComparable.CompareTo (object value);
Function CompareTo (value As Object) As Integer Implements IComparable.CompareTo

Parámetros

value
Object

Un objeto que se evalúa como un objeto String.An object that evaluates to a String.

Devoluciones

Entero con signo de 32 bits que indica si la posición de esta instancia es anterior, posterior o igual que la posición del parámetro value en el criterio de ordenación.A 32-bit signed integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the value parameter.

ValueValueCondiciónCondition
Menor que ceroLess than zeroEsta instancia precede a value.This instance precedes value.
CeroZeroEn el criterio de ordenación, esta instancia tiene la misma posición que value.This instance has the same position in the sort order as value.
Mayor que ceroGreater than zeroEsta instancia es posterior a value.This instance follows value.

O bien-or-

value es null.value is null.

Implementaciones

Excepciones

value no es un String.value is not a String.

Ejemplos

En el ejemplo siguiente se usa el método CompareTo con un Object.The following example uses the CompareTo method with an Object. Dado que intenta comparar una instancia de String con un objeto TestClass, el método produce una ArgumentException.Because it attempts to compare a String instance to a TestClass object, the method throws an ArgumentException.

using namespace System;

public ref class TestClass{};

int main()
{
   TestClass^ test = gcnew TestClass;
   array<Object^>^ objectsToCompare = { test, test->ToString(), 123,
                                        (123).ToString(), "some text",
                                        "Some Text" };
   String^ s = "some text";
   for each (Object^ objectToCompare in objectsToCompare) {
      try {
         Int32 i = s->CompareTo(objectToCompare);
         Console::WriteLine("Comparing '{0}' with '{1}': {2}",
                            s, objectToCompare, i);
      }
      catch (ArgumentException^ e) {
         Console::WriteLine("Bad argument: {0} (type {1})",
                            objectToCompare,
                            objectToCompare->GetType()->Name);
      }
   }
}
// The example displays the following output:
//    Bad argument: TestClass (type TestClass)
//    Comparing 'some text' with 'TestClass': -1
//    Bad argument: 123 (type Int32)
//    Comparing 'some text' with '123': 1
//    Comparing 'some text' with 'some text': 0
//    Comparing 'some text' with 'Some Text': -1
using System;

public class TestClass
{}

public class Example 
{
   public static void Main()
   {
      var test = new TestClass();
      Object[] objectsToCompare = { test, test.ToString(), 123,
                                    123.ToString(), "some text",
                                    "Some Text" };
      string s = "some text";
      foreach (var objectToCompare in objectsToCompare) {
         try {
            int i = s.CompareTo(objectToCompare);
            Console.WriteLine("Comparing '{0}' with '{1}': {2}",
                              s, objectToCompare, i);
         }
         catch (ArgumentException) {
            Console.WriteLine("Bad argument: {0} (type {1})",
                              objectToCompare,
                              objectToCompare.GetType().Name);
         }
      }
   }
}
// The example displays the following output:
//    Bad argument: TestClass (type TestClass)
//    Comparing 'some text' with 'TestClass': -1
//    Bad argument: 123 (type Int32)
//    Comparing 'some text' with '123': 1
//    Comparing 'some text' with 'some text': 0
//    Comparing 'some text' with 'Some Text': -1
Public Class TestClass
End Class 


Public Class Example
   Public Shared Sub Main()
      Dim test As New TestClass()
      Dim objectsToCompare() As Object = { test, test.ToString(), 123,
                                           123.ToString(), "some text",
                                           "Some Text" }
      Dim s As String = "some text"
      For Each objectToCompare In objectsToCompare
         Try
            Dim i As Integer = s.CompareTo(objectToCompare)
            Console.WriteLine("Comparing '{0}' with '{1}': {2}",
                              s, objectToCompare, i)
         Catch e As ArgumentException
            Console.WriteLine("Bad argument: {0} (type {1})",
                              objectToCompare,
                              objectToCompare.GetType().Name)
         End Try
      Next
   End Sub 
End Class 
' The example displays the following output:
'       Bad argument: TestClass (type TestClass)
'       Comparing 'some text' with 'TestClass': -1
'       Bad argument: 123 (type Int32)
'       Comparing 'some text' with '123': 1
'       Comparing 'some text' with 'some text': 0
'       Comparing 'some text' with 'Some Text': -1

Comentarios

value debe ser un objeto String.value must be a String object.

Precaución

El método de CompareTo se diseñó principalmente para su uso en operaciones de ordenación o de ordenación alfabética.The CompareTo method was designed primarily for use in sorting or alphabetizing operations. No se debe usar cuando el propósito principal de la llamada al método es determinar si dos cadenas son equivalentes.It should not be used when the primary purpose of the method call is to determine whether two strings are equivalent. Para determinar si dos cadenas son equivalentes, llame al método Equals.To determine whether two strings are equivalent, call the Equals method.

Este método realiza una comparación de Word (con distinción de mayúsculas y minúsculas y con la referencia cultural) utilizando la referencia cultural actual.This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture. Para obtener más información acerca de las ordenaciones de palabras, cadenas y ordinales, vea System.Globalization.CompareOptions.For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

Para obtener más información sobre el comportamiento de este método, vea la sección Comentarios del método String.Compare(String, String).For more information about the behavior of this method, see the Remarks section of the String.Compare(String, String) method.

Se aplica a