IComparable<T> インターフェイス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
インスタンスを並べ替えたり並べ替えたりするための型固有の比較メソッドを作成するために、値の型またはクラスが実装する一般化された比較メソッドを定義します。
generic <typename T>
public interface class IComparable
public interface IComparable<in T>
public interface IComparable<in T> where T : allows ref struct
public interface IComparable<T>
type IComparable<'T> = interface
Public Interface IComparable(Of In T)
Public Interface IComparable(Of T)
型パラメーター
- T
比較するオブジェクトの型。
この型パラメーターは反変です。 つまり、指定した型、または弱い派生型のいずれかを使用することができます。 共変性および反変性の詳細については、「ジェネリックの共変性と反変性」をご覧ください。- 派生
例
次の例は、単純なIComparable<T> オブジェクトのTemperatureの実装を示しています。 この例では、SortedList<TKey,TValue> オブジェクト キーを持つ文字列のTemperatureコレクションを作成し、複数の温度と文字列のペアを順序外のリストに追加します。
Add メソッドの呼び出しでは、SortedList<TKey,TValue> コレクションは、IComparable<T>実装を使用してリスト エントリを並べ替え、温度を上げる順序で表示されます。
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.
*/
open System
open System.Collections.Generic
type Temperature(kelvins: double) =
// The underlying temperature value.
let mutable kelvins = kelvins
do
if kelvins < 0. then
invalidArg (nameof kelvins) "Temperature cannot be less than absolute zero."
// Define the is greater than operator.
static member op_GreaterThan (operand1: Temperature, operand2: Temperature) =
operand1.CompareTo operand2 > 0
// Define the is less than operator.
static member op_LessThan (operand1: Temperature, operand2: Temperature) =
operand1.CompareTo operand2 < 0
// Define the is greater than or equal to operator.
static member op_GreaterThanOrEqual (operand1: Temperature, operand2: Temperature) =
operand1.CompareTo operand2 >= 0
// Define the is less than or equal to operator.
static member op_LessThanOrEqual (operand1: Temperature, operand2: Temperature) =
operand1.CompareTo operand2 <= 0
member _.Celsius =
kelvins - 273.15
member _.Kelvin
with get () =
kelvins
and set (value) =
if value < 0. then
invalidArg (nameof value) "Temperature cannot be less than absolute zero."
else
kelvins <- value
// Implement the generic CompareTo method with the Temperature
// class as the Type parameter.
member _.CompareTo(other: Temperature) =
// If other is not a valid object reference, this instance is greater.
match box other with
| null -> 1
| _ ->
// The temperature comparison depends on the comparison of
// the underlying Double values.
kelvins.CompareTo(other.Kelvin)
interface IComparable<Temperature> with
member this.CompareTo(other) = this.CompareTo other
let temps = SortedList()
// Add entries to the sorted list, out of order.
temps.Add(Temperature 2017.15, "Boiling point of Lead")
temps.Add(Temperature 0., "Absolute zero")
temps.Add(Temperature 273.15, "Freezing point of water")
temps.Add(Temperature 5100.15, "Boiling point of Carbon")
temps.Add(Temperature 373.15, "Boiling point of water")
temps.Add(Temperature 600.65, "Melting point of Lead")
for kvp in temps do
printfn $"{kvp.Value} is {kvp.Key.Celsius} degrees 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.
Imports System.Collections.Generic
Public Class Temperature
Implements IComparable(Of Temperature)
' Implement the generic CompareTo method with the Temperature class
' as the type parameter.
'
Public Overloads Function CompareTo(ByVal other As Temperature) As Integer _
Implements IComparable(Of Temperature).CompareTo
' If other is not a valid object reference, this instance is greater.
If other Is Nothing Then Return 1
' The temperature comparison depends on the comparison of the
' the underlying Double values.
Return m_value.CompareTo(other.m_value)
End Function
' Define the is greater than operator.
Public Shared Operator > (operand1 As Temperature, operand2 As Temperature) As Boolean
Return operand1.CompareTo(operand2) > 0
End Operator
' Define the is less than operator.
Public Shared Operator < (operand1 As Temperature, operand2 As Temperature) As Boolean
Return operand1.CompareTo(operand2) < 0
End Operator
' Define the is greater than or equal to operator.
Public Shared Operator >= (operand1 As Temperature, operand2 As Temperature) As Boolean
Return operand1.CompareTo(operand2) >= 0
End Operator
' Define the is less than operator.
Public Shared Operator <= (operand1 As Temperature, operand2 As Temperature) As Boolean
Return operand1.CompareTo(operand2) <= 0
End Operator
' The underlying temperature value.
Protected m_value As Double = 0.0
Public ReadOnly Property Celsius() As Double
Get
Return m_value - 273.15
End Get
End Property
Public Property Kelvin() As Double
Get
Return m_value
End Get
Set(ByVal Value As Double)
If value < 0.0 Then
Throw New ArgumentException("Temperature cannot be less than absolute zero.")
Else
m_value = Value
End If
End Set
End Property
Public Sub New(ByVal kelvins As Double)
Me.Kelvin = kelvins
End Sub
End Class
Public Class Example
Public Shared Sub Main()
Dim temps As New SortedList(Of 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")
For Each kvp As KeyValuePair(Of Temperature, String) In temps
Console.WriteLine("{0} is {1} degrees Celsius.", kvp.Value, kvp.Key.Celsius)
Next
End Sub
End Class
' The 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.
'
注釈
このインターフェイスは、値を並べ替えたり並べ替えたりできる型によって実装され、ジェネリック コレクション オブジェクトのメンバーを順序付けするための厳密に型指定された比較メソッドを提供します。 たとえば、1 つの数値は 2 番目の数値より大きくすることができ、1 つの文字列は別の文字列の前にアルファベット順に表示できます。 型を実装するには、並べ替え順序での現在のインスタンスの位置が、同じ型の 2 番目のオブジェクトの前、後、または同じかどうかを示す単一のメソッド ( CompareTo(T)) を定義する必要があります。 通常、メソッドは開発者コードから直接呼び出されません。 代わりに、 List<T>.Sort() や Addなどのメソッドによって自動的に呼び出されます。
通常、 IComparable<T> 実装を提供する型は、 IEquatable<T> インターフェイスも実装します。 IEquatable<T> インターフェイスは、実装する型のインスタンスの等価性を決定するEquals メソッドを定義します。
CompareTo(T) メソッドの実装では、次の表に示すように、3 つの値のいずれかを持つInt32を返す必要があります。
| 価値 | 意味 |
|---|---|
| 0 より小 | このオブジェクトは、並べ替え順序で CompareTo メソッドで指定されたオブジェクトの前にあります。 |
| ゼロ | この現在のインスタンスは、 CompareTo メソッド引数で指定されたオブジェクトと同じ並べ替え順序で発生します。 |
| 0 より大 | この現在のインスタンスは、並べ替え順序で CompareTo メソッド引数で指定されたオブジェクトに従います。 |
すべての数値型 (Int32やDoubleなど) は、IComparable<T>、String、Charと同様に、DateTimeを実装します。 カスタム型では、オブジェクト インスタンスの順序付けまたは並べ替えを可能にする独自の IComparable<T> の実装も提供する必要があります。
注意 (実装者)
IComparable<T> インターフェイスの型パラメーターを、このインターフェイスを実装している型に置き換えます。
IComparable<T>を実装する場合は、op_GreaterThan、op_GreaterThanOrEqual、op_LessThan、およびop_LessThanOrEqual演算子をオーバーロードして、CompareTo(T)と一致する値を返す必要があります。 さらに、 IEquatable<T>も実装する必要があります。 詳細については、 IEquatable<T> の記事を参照してください。
メソッド
| 名前 | 説明 |
|---|---|
| CompareTo(T) |
現在のインスタンスを同じ型の別のオブジェクトと比較し、現在のインスタンスが並べ替え順序で他のオブジェクトと同じ位置にあるかどうかを示す整数を返します。 |