C#にてIComparable, IComparable<T> インターフェースの実装について説明します。
IComparable<T>はIComparableのジェネリックです。
配列(Array)などのコンテナークラスでは数値等を格納した場合はソート等ができます。
IComparable、IComparable<T>を継承すれば、自作のクラスでもこれらの機能が使えます。
IComparableインターフェイスには、CompareToメソッドしかありません。のでこれを実装します。
IComparableの実装
class Person : IComparable, IComparable<Person>
{
//コンストラクタ
public Person(string personName)
{
this._name = personName;
}
public string Name
{
get
{
return this._name;
}
}
private string _name;
public int CompareTo(object other)
{
return _name.CompareTo(((Person)other).Name);
}
public int CompareTo(Person other)
{
return _name.CompareTo(other.Name);
}
}
上の実装で
CompareTo(object other)がIComparableに
CompareTo(Person other)が IComparable<Person>に相当します。
またArrayListのSortはCompareTo(object other)を使用して並び替えます。
呼び出し側
private void button2_Click(object sender, EventArgs e)
{
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(new Person("もも"));
al.Add(new Person("リンゴ"));
al.Add(new Person("ナシ"));
al.Sort();
}