更新 : 2010 年 6 月
2 つのオブジェクトを比較するために型が実装するメソッドを定義します。
アセンブリ: mscorlib (mscorlib.dll 内)
Public Interface IComparer(Of In T)
public interface IComparer<in T>
generic<typename T> public interface class IComparer
type IComparer<'T> = interface end
型パラメーター
- in T
-
比較するオブジェクトの型。
このパラメーターが反変の型パラメーターです。 つまり、その指定した型を使用するか、それよりも弱い任意の派生型を使用することができます。 共変性と反変性の詳細については、「ジェネリックの共変性と反変性」を参照してください。
IComparer<T> 型で公開されるメンバーは以下のとおりです。
| 名前 | 説明 | |
|---|---|---|
|
Compare | 2 つのオブジェクトを比較し、一方が他方より小さいか、等しいか、大きいかを示す値を返します。 |
このインターフェイスは、List<T>.Sort メソッドおよび List<T>.BinarySearch メソッドで使用されます。 このインターフェイスを使用すると、コレクションの並べ替え順序をカスタマイズできます。 このインターフェイスを実装するクラスには、SortedDictionary<TKey, TValue> ジェネリック クラスと SortedList<TKey, TValue> ジェネリック クラスが含まれます。
このインターフェイスの既定の実装は、Comparer<T> クラスです。 StringComparer クラスは、このインターフェイスを String 型に対して実装します。
このインターフェイスは、順序の比較をサポートします。 つまり、Compare メソッドが 0 を返す場合、2 つのオブジェクトは同じように並べ替えられます。 厳密な等値比較の実装は、IEqualityComparer<T> ジェネリック インターフェイスで提供されます。
IComparer<T> インターフェイスを実装する代わりに Comparer<T> クラスから派生させることをお勧めします。Comparer<T> クラスでは、IComparer.Compare メソッドの明示的なインターフェイス実装と、オブジェクトの既定比較演算子を取得する Default プロパティが用意されるためです。
次の例では、IComparer<T> インターフェイスを実装して、型 Box のオブジェクトを寸法によって比較します。 このコード例は、Comparer<T> クラスのトピックで取り上げているコード例の一部分です。
' This class is not demonstrated in the Main method ' and is provided only to show how to implement ' the interface. It is recommended to derive ' from Comparer<T> instead of implementing IComparer<T>. Public Class BoxComp Implements IComparer(Of Box) ' Compares by Height, Length, and Width. Public Function Compare(ByVal x As Box, ByVal y As Box) As Integer Implements _ IComparer(Of Box).Compare If x.Height.CompareTo(y.Height) <> 0 Then Return x.Height.CompareTo(y.Height) ElseIf x.Length.CompareTo(y.Length) <> 0 Then Return x.Length.CompareTo(y.Length) ElseIf x.Width.CompareTo(y.Width) <> 0 Then Return x.Width.CompareTo(y.Width) Else Return 0 End If End Function End Class
// This class is not demonstrated in the Main method // and is provided only to show how to implement // the interface. It is recommended to derive // from Comparer<T> instead of implementing IComparer<T>. public class BoxComp : IComparer<Box> { // Compares by Height, Length, and Width. public int Compare(Box x, Box y) { if (x.Height.CompareTo(y.Height) != 0) { return x.Height.CompareTo(y.Height); } else if (x.Length.CompareTo(y.Length) != 0) { return x.Length.CompareTo(y.Length); } else if (x.Width.CompareTo(y.Width) != 0) { return x.Width.CompareTo(y.Width); } else { return 0; } } }
.NET Framework
サポート対象: 4、3.5、3.0、2.0.NET Framework Client Profile
サポート対象: 4、3.5 SP1サポート対象:
Windows 7, Windows Vista SP1 以降, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core はサポート対象外), Windows Server 2008 R2 (SP1 以降で Server Core をサポート), Windows Server 2003 SP2
.NET Framework では、各プラットフォームのすべてのバージョンはサポートしていません。 サポートされているバージョンについては、「.NET Framework システム要件」を参照してください。
参照
|
日付 |
History |
理由 |
|---|---|---|
|
2010 年 6 月 |
解説が更新され、例が追加されました。 |
情報の拡充 |