实现
class Preson : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(object other)
{
Preson otherz = other as Preson;
return Age.CompareTo(otherz.Age);
}
int IComparable.CompareTo(object obj)
{
Preson otherz = obj as Preson;
return Name.CompareTo(otherz.Name);
}
public override string ToString()
{
return Name + "----" + Age.ToString() + "\r\n";
}
}
static void Main(string[] args)
{
ArrayList studentList = new ArrayList();
studentList.Add(new Preson() { Age = 1, Name = "a1" });
studentList.Add(new Preson() { Age = 5, Name = "g1" });
studentList.Add(new Preson() { Age = 4, Name = "b1" });
studentList.Add(new Preson() { Age = 2, Name = "f1" });
studentList.Sort();
foreach (Preson item in studentList)
{
Console.Write(item.ToString());
}
}
结果:
可以看出是按Name字段排序的,也就是说默认是按实现显示接口的方法。
Icomparer也是一样,大家可以试一试,
如有错误,请大家批评指正