閱讀英文版本

分享方式:


IComparable<T> 介面

定義

定義通用的比較方法,實值型別或類別會實作這個方法,以建立特定類型的比較方法來排序其執行個體。

C#
public interface IComparable<in T>
C#
public interface IComparable<T>

類型參數

T

要比較之物件的類型。

這是反變數的型別參數。 也就是說,您可以使用您指定的類型,或衍生程度較低的任何類型。 如需共變數與反變數的詳細資訊,請參閱泛型中的共變數與反變數
衍生

範例

下列範例說明簡單 Temperature 物件的 實 IComparable<T> 作。 此範例會建立 SortedList<TKey,TValue> 具有 Temperature 物件索引鍵的字串集合,並將陣列溫度和字串新增至序列外的清單。 在呼叫 方法時 AddSortedList<TKey,TValue> 集合會 IComparable<T> 使用 實作來排序清單專案,然後依溫度增加的順序顯示。

C#
using System;
using System.Collections.Generic;

public class Temperature : IComparable<Temperature>
{
    // Implement the generic CompareTo method with the Temperature
    // class as the Type parameter.
    //
    public int CompareTo(Temperature other)
    {
        // If other is not a valid object reference, this instance is greater.
        if (other == null) return 1;

        // The temperature comparison depends on the comparison of
        // the underlying Double values.
        return m_value.CompareTo(other.m_value);
    }

    // Define the is greater than operator.
    public static bool operator >  (Temperature operand1, Temperature operand2)
    {
       return operand1.CompareTo(operand2) > 0;
    }

    // Define the is less than operator.
    public static bool operator <  (Temperature operand1, Temperature operand2)
    {
       return operand1.CompareTo(operand2) < 0;
    }

    // Define the is greater than or equal to operator.
    public static bool operator >=  (Temperature operand1, Temperature operand2)
    {
       return operand1.CompareTo(operand2) >= 0;
    }

    // Define the is less than or equal to operator.
    public static bool operator <=  (Temperature operand1, Temperature operand2)
    {
       return operand1.CompareTo(operand2) <= 0;
    }

    // The underlying temperature value.
    protected double m_value = 0.0;

    public double Celsius
    {
        get
        {
            return m_value - 273.15;
        }
    }

    public double Kelvin
    {
        get
        {
            return m_value;
        }
        set
        {
            if (value < 0.0)
            {
                throw new ArgumentException("Temperature cannot be less than absolute zero.");
            }
            else
            {
                m_value = value;
            }
        }
    }

    public Temperature(double kelvins)
    {
        this.Kelvin = kelvins;
    }
}

public class Example
{
    public static void Main()
    {
        SortedList<Temperature, string> temps =
            new SortedList<Temperature, string>();

        // Add entries to the sorted list, out of order.
        temps.Add(new Temperature(2017.15), "Boiling point of Lead");
        temps.Add(new Temperature(0), "Absolute zero");
        temps.Add(new Temperature(273.15), "Freezing point of water");
        temps.Add(new Temperature(5100.15), "Boiling point of Carbon");
        temps.Add(new Temperature(373.15), "Boiling point of water");
        temps.Add(new Temperature(600.65), "Melting point of Lead");

        foreach( KeyValuePair<Temperature, string> kvp in temps )
        {
            Console.WriteLine("{0} is {1} degrees Celsius.", kvp.Value, kvp.Key.Celsius);
        }
    }
}
/* This example displays the following output:
      Absolute zero is -273.15 degrees Celsius.
      Freezing point of water is 0 degrees Celsius.
      Boiling point of water is 100 degrees Celsius.
      Melting point of Lead is 327.5 degrees Celsius.
      Boiling point of Lead is 1744 degrees Celsius.
      Boiling point of Carbon is 4827 degrees Celsius.
*/

備註

這個介面是由可排序或排序值的型別實作,並提供強型別比較方法來排序泛型集合物件的成員。 例如,一個數位可以大於第二個數字,而一個字串可以依字母順序出現在另一個字串之前。 它要求實作型別會定義單一方法 , CompareTo(T) 指出目前實例在排序次序中的位置是之前、之後,還是與相同類型的第二個物件相同。 一般而言,方法不會直接從開發人員程式碼呼叫。 相反地,它會由 和 Add 之類的 List<T>.Sort() 方法自動呼叫。

一般而言,提供實作 IComparable<T> 的類型也會實作 IEquatable<T> 介面。 介面 IEquatable<T>Equals 定義 方法,這個方法會決定實作類型的實例相等。

方法的實作 CompareTo(T) 必須傳回 Int32 具有三個值之一的 ,如下表所示。

意義
小於零 這個物件在排序次序中方法所 CompareTo 指定的物件之前。
這個目前的實例會以與方法引數所 CompareTo 指定物件相同的排序次序位置發生。
大於零 這個目前的實例會遵循排序次序中方法引數所 CompareTo 指定的 物件。

所有數數值型別 (例如 和) 實 IComparable<T> 作 、,如 、 CharString 、 和 DateTimeDoubleInt32 自訂類型也應該提供自己的 實 IComparable<T> 作,讓物件實例能夠排序或排序。

給實施者的注意事項

將 介面的類型 IComparable<T> 參數取代為實作這個介面的類型。

如果您實作 IComparable<T> ,則應該多載 op_GreaterThanop_GreaterThanOrEqualop_LessThanop_LessThanOrEqual 運算子,以傳回與 一 CompareTo(T) 致的值。 此外,您也應該實作 IEquatable<T> 。 如需完整資訊,請參閱文章 IEquatable<T>

方法

CompareTo(T)

將目前的執行個體與相同類型的另一個物件相比較,並傳回整數,這個整數表示目前的執行個體在排序次序中,位於另一個物件之前、之後或相同位置。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱