CompareTo 方法逻辑如何在 List 排序函数中工作。
public class person : IComparable
{
string firstName;
string lastName;
public int CompareTo(object obj)
{
person otherPerson = (person)obj;
if (this.lastName != otherPerson.lastName)
return this.lastName.CompareTo(otherPerson.lastName);
else
return this.firstName.CompareTo(otherPerson.firstName);
}
public person(string _firstName, string _lastName)
{
firstName = _firstName;
lastName = _lastName;
}
override public string ToString()
{
return firstName + " " + lastName;
}
}
List<person> l = new List<person>();
l.Add(new person("Mark", "Hanson"));
l.Add(new person("Kim", "Akers"));
l.Add(new person("Zsolt", "Ambrus"));
l.Sort();
foreach (person p in l)
Console.WriteLine(p.ToString());