다음을 통해 공유


IComparable.CompareTo(Object) 메서드

정의

현재 인스턴스를 동일한 형식의 다른 개체와 비교하고 현재 인스턴스가 다른 개체와 정렬 순서의 동일한 위치에서 선행, 팔로우 또는 발생하는지 여부를 나타내는 정수를 반환합니다.

public:
 int CompareTo(System::Object ^ obj);
public int CompareTo (object obj);
public int CompareTo (object? obj);
abstract member CompareTo : obj -> int
Public Function CompareTo (obj As Object) As Integer

매개 변수

obj
Object

이 인스턴스와 비교할 개체입니다.

반환

비교할 개체의 상대 순서를 나타내는 값입니다. 반환 값에는 다음과 같은 의미가 있습니다.

의미
0보다 작음 이 인스턴스는 정렬 순서로 obj 앞에 섰습니다.
이 인스턴스는 obj정렬 순서와 동일한 위치에서 발생합니다.
0보다 큼 이 인스턴스는 정렬 순서의 obj 따릅니다.

예외

obj 이 인스턴스와 형식이 다릅니다.

예제

다음 예제에서는 CompareTo 사용하여 IComparable 구현하는 Temperature 개체를 다른 개체와 비교하는 방법을 보여 줍니다. Temperature 개체는 단순히 Int32.CompareTo 메서드에 대한 호출을 래핑하여 CompareTo 구현합니다.

using namespace System;
using namespace System::Collections;

public ref class Temperature: public IComparable {
   /// <summary>
   /// IComparable.CompareTo implementation.
   /// </summary>
protected:
   // The value holder
   Double m_value;

public:
   virtual Int32 CompareTo( Object^ obj ) {
   
      if (obj == nullptr) return 1;
      
      if ( obj->GetType() == Temperature::typeid ) {
         Temperature^ temp = dynamic_cast<Temperature^>(obj);

         return m_value.CompareTo( temp->m_value );
      }
      throw gcnew ArgumentException(  "object is not a Temperature" );
   }

   property Double Value {
      Double get() {
         return m_value;
      }
      void set( Double value ) {
         m_value = value;
      }
   }

   property Double Celsius  {
      Double get() {
         return (m_value - 32) / 1.8;
      }
      void set( Double value ) {
         m_value = (value * 1.8) + 32;
      }
   }
};

int main()
{
   ArrayList^ temperatures = gcnew ArrayList;
   // Initialize random number generator.
   Random^ rnd = gcnew Random;

   // Generate 10 temperatures between 0 and 100 randomly.
   for (int ctr = 1; ctr <= 10; ctr++)
   {
      int degrees = rnd->Next(0, 100);
      Temperature^ temp = gcnew Temperature;
      temp->Value = degrees;
      temperatures->Add(temp);
   }

   // Sort ArrayList.
   temperatures->Sort();
      
   for each (Temperature^ temp in temperatures)
      Console::WriteLine(temp->Value);
   return 0;
}
// The example displays the following output to the console (individual
// values may vary because they are randomly generated):
//       2
//       7
//       16
//       17
//       31
//       37
//       58
//       66
//       72
//       95
using System;
using System.Collections;

public class Temperature : IComparable
{
    // The temperature value
    protected double temperatureF;

    public int CompareTo(object obj) {
        if (obj == null) return 1;

        Temperature otherTemperature = obj as Temperature;
        if (otherTemperature != null)
            return this.temperatureF.CompareTo(otherTemperature.temperatureF);
        else
           throw new ArgumentException("Object is not a Temperature");
    }

    public double Fahrenheit
    {
        get
        {
            return this.temperatureF;
        }
        set 
        {
            this.temperatureF = value;
        }
    }

    public double Celsius
    {
        get
        {
            return (this.temperatureF - 32) * (5.0/9);
        }
        set
        {
            this.temperatureF = (value * 9.0/5) + 32;
        }
    }
}

public class CompareTemperatures
{
   public static void Main()
   {
      ArrayList temperatures = new ArrayList();
      // Initialize random number generator.
      Random rnd = new Random();

      // Generate 10 temperatures between 0 and 100 randomly.
      for (int ctr = 1; ctr <= 10; ctr++)
      {
         int degrees = rnd.Next(0, 100);
         Temperature temp = new Temperature();
         temp.Fahrenheit = degrees;
         temperatures.Add(temp);
      }

      // Sort ArrayList.
      temperatures.Sort();

      foreach (Temperature temp in temperatures)
         Console.WriteLine(temp.Fahrenheit);
   }
}
// The example displays the following output to the console (individual
// values may vary because they are randomly generated):
//       2
//       7
//       16
//       17
//       31
//       37
//       58
//       66
//       72
//       95
open System
open System.Collections

type Temperature() =
    // The temperature value
    let mutable temperatureF = 0.

    interface IComparable with
        member _.CompareTo(obj) =
            match obj with 
            | null -> 1
            | :? Temperature as other -> 
                temperatureF.CompareTo other.Fahrenheit
            | _ ->
                invalidArg (nameof obj) "Object is not a Temperature"

    member _.Fahrenheit 
        with get () =
            temperatureF
        and set (value) = 
            temperatureF <- value

    member _.Celsius
        with get () =
            (temperatureF - 32.) * (5. / 9.)
        and set (value) =
            temperatureF <- (value * 9. / 5.) + 32.

let temperatures = ResizeArray()

// Initialize random number generator.
let rnd = Random()

// Generate 10 temperatures between 0 and 100 randomly.
for _ = 1 to 10 do
    let degrees = rnd.Next(0, 100)
    let temp = Temperature(Fahrenheit=degrees)
    temperatures.Add temp

// Sort ResizeArray.
temperatures.Sort()

for temp in temperatures do
    printfn $"{temp.Fahrenheit}"

// The example displays the following output to the console (individual
// values may vary because they are randomly generated):
//       2
//       7
//       16
//       17
//       31
//       37
//       58
//       66
//       72
//       95
Imports System.Collections

Public Class Temperature
    Implements IComparable
    ' The temperature value
    Protected temperatureF As Double

    Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
        Implements IComparable.CompareTo
        
        If obj Is Nothing Then Return 1

        Dim otherTemperature As Temperature = TryCast(obj, Temperature)
        If otherTemperature IsNot Nothing Then
            Return Me.temperatureF.CompareTo(otherTemperature.temperatureF)
        Else
           Throw New ArgumentException("Object is not a Temperature")
        End If   
    End Function

    Public Property Fahrenheit() As Double
        Get
            Return temperatureF
        End Get
        Set(ByVal Value As Double)
            Me.temperatureF = Value
        End Set
    End Property

    Public Property Celsius() As Double
        Get
            Return (temperatureF - 32) * (5/9)
        End Get
        Set(ByVal Value As Double)
            Me.temperatureF = (Value * 9/5) + 32
        End Set
    End Property
End Class

Public Module CompareTemperatures
   Public Sub Main()
      Dim temperatures As New ArrayList
      ' Initialize random number generator.
      Dim rnd As New Random()
      
      ' Generate 10 temperatures between 0 and 100 randomly.
      For ctr As Integer = 1 To 10
         Dim degrees As Integer = rnd.Next(0, 100)
         Dim temp As New Temperature
         temp.Fahrenheit = degrees
         temperatures.Add(temp)   
      Next

      ' Sort ArrayList.
      temperatures.Sort()
      
      For Each temp As Temperature In temperatures
         Console.WriteLine(temp.Fahrenheit)
      Next      
   End Sub
End Module
' The example displays the following output to the console (individual
' values may vary because they are randomly generated):
'       2
'       7
'       16
'       17
'       31
'       37
'       58
'       66
'       72
'       95

설명

CompareTo 메서드는 값을 정렬하거나 정렬할 수 있는 형식에 의해 구현됩니다. 배열의 각 멤버를 정렬하기 위해 Array.Sort같은 제네릭이 아닌 컬렉션 개체의 메서드에 의해 자동으로 호출됩니다. 사용자 지정 클래스 또는 구조체가 IComparable구현하지 않으면 해당 멤버를 정렬할 수 없으며 정렬 작업에서 InvalidOperationExceptionthrow할 수 있습니다.

이 메서드는 정의일 뿐이며 영향을 주려면 특정 클래스 또는 값 형식에 의해 구현되어야 합니다. 반환 값 섹션에 지정된 비교의 의미("precedes", "occurs in the same position as", and "follows")는 특정 구현에 따라 달라집니다.

정의에 따라 모든 개체가 null보다 크거나 뒤를 잇고 두 개의 null 참조가 서로 비교됩니다.

obj매개 변수는 이 인터페이스를 구현하는 클래스 또는 값 형식과 동일한 형식이어야 합니다. 그렇지 않으면 ArgumentException throw됩니다.

구현자 참고

개체 A, B 및 C의 경우 다음이 true여야 합니다.

A.CompareTo(A) 0을 반환해야 합니다.

A.CompareTo(B) 0을 반환하는 경우 B.CompareTo(A) 0을 반환해야 합니다.

A.CompareTo(B) 0을 반환하고 B.CompareTo(C) 0을 반환하는 경우 A.CompareTo(C) 0을 반환해야 합니다.

A.CompareTo(B) 0이 아닌 값을 반환하는 경우 B.CompareTo(A) 반대 기호의 값을 반환해야 합니다.

A.CompareTo(B) 값 "x"가 0이 아닌 값을 반환하고 B.CompareTo(C) "x"와 같은 부호의 "y" 값을 반환하는 경우 A.CompareTo(C) "x" 및 "y"와 동일한 부호의 값을 반환해야 합니다.

호출자 참고

CompareTo(Object) 메서드를 사용하여 클래스 인스턴스의 순서를 확인합니다.

적용 대상

추가 정보