IComparable
( 、IComparer
、IEquatable
、IEnumerable
)などの標準の c# インターフェイスを明示的に実装する必要がありますIEnumerator
。私はそれを正しくやっていますか?
class Lemon : IComparable
{
public String name { get; set; }
public int id { get; set; }
public Lemon (String name, int id)
{
this.name = name;
this.id = id;
}
int IComparable.CompareTo(object obj)
{
Lemon other = (Lemon)obj;
if (this.id > other.id)
return 1;
else if (this.id < other.id)
return -1;
else return 0;
}
public void diamond ()
{
Console.WriteLine();
}
public override string ToString()
{
return this.name + " " + this.id;
}
}
そして今メイン:
static void Main(string[] args)
{
List<IComparable> icL = new List<IComparable>();
IComparable temp = new Lemon("Git", 99);
icL.Add(temp);
icL.Add(new Lemon("Green", 9));
icL.Add(new Lemon("Don", 7));
icL.Add(new Lemon("Simon", 12));
icL.Sort();
foreach (IComparable itm in icL)
{
Console.WriteLine(itm.ToString());
}
Console.WriteLine("----------");
}
それで、あなたはどう思いますか?
もう 1 つの問題は、コレクションを繰り返し処理しているときに、メソッド diamond にどのようにアクセスできるかということです。