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 Object especificado en el criterio de ordenación.

 virtual int System.IComparable.CompareTo(System::Object ^ value) = IComparable::CompareTo;
int IComparable.CompareTo (object value);
abstract member System.IComparable.CompareTo : obj -> int
override this.System.IComparable.CompareTo : obj -> int
Function CompareTo (value As Object) As Integer Implements IComparable.CompareTo

Parámetros

value
Object

Un objeto que se evalúa como un objeto 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.

ValorCondición
Menor que ceroEsta instancia precede a value.
CeroEn el criterio de ordenación, esta instancia tiene la misma posición que value.
Mayor que ceroEsta instancia es posterior a value, o bien value es null.

Implementaciones

Excepciones

value no es un String.

Ejemplos

En el ejemplo siguiente se usa el CompareTo método con .Object Dado que intenta comparar una String instancia con un TestClass objeto , el método produce una ArgumentExceptionexcepción .

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
open System

type TestClass() = class end

let test = TestClass()
let objectsToCompare: obj list =
    [ test; string test; 123
      string 123; "some text"
      "Some Text" ]
let s = "some text"
for objectToCompare in objectsToCompare do
    try
        let i = s.CompareTo objectToCompare
        printfn $"Comparing '{s}' with '{objectToCompare}': {i}"
    with :? ArgumentException ->
        printfn $"Bad argument: {objectToCompare} (type {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 String objeto .

Precaución

El CompareTo método se diseñó principalmente para su uso en operaciones de ordenación o alfabética. No se debe usar cuando el propósito principal de la llamada al método es determinar si dos cadenas son equivalentes. Para determinar si dos cadenas son equivalentes, llame al Equals método .

Este método realiza una comparación de palabras (distingue mayúsculas de minúsculas y distingue referencias culturales) mediante la referencia cultural actual. Para obtener más información sobre las ordenación de palabras, cadenas y ordinales, vea System.Globalization.CompareOptions.

Para obtener más información sobre el comportamiento de este método, vea la sección Comentarios del String.Compare(String, String) método .

Se aplica a