对于ArrayList.Sort()使用每个元素的 IComparable 实现对整个 ArrayList 中的元素进行排序。蛤是它的内部实现过程不太明白,请教一下有没有人可以详细的告诉我一下,在内部的每次比较的元素和结果,谢谢!
代码如下:
Person.cs中:
class Person:IComparable
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
} public int CompareTo(object obj)
{
if (obj is Person)
{
Person otherPerson = obj as Person;
return this.Age-otherPerson.Age;
}
else
{
throw new ArgumentException(
"Object to compare to is not a Person object.");
}
}
}
Program.cs中:
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(new Person("Jim",30));
list.Add(new Person("Bob", 25));
list.Add(new Person("Bert", 27));
list.Add(new Person("Ernie", 22)); list.Sort();
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine("{0} ({1})", (list[i] as Person).Name, (list[i] as Person).Age);
}
Console.WriteLine();
}
}
代码如下:
Person.cs中:
class Person:IComparable
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
} public int CompareTo(object obj)
{
if (obj is Person)
{
Person otherPerson = obj as Person;
return this.Age-otherPerson.Age;
}
else
{
throw new ArgumentException(
"Object to compare to is not a Person object.");
}
}
}
Program.cs中:
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(new Person("Jim",30));
list.Add(new Person("Bob", 25));
list.Add(new Person("Bert", 27));
list.Add(new Person("Ernie", 22)); list.Sort();
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine("{0} ({1})", (list[i] as Person).Name, (list[i] as Person).Age);
}
Console.WriteLine();
}
}
大于 1
小于 -1
大于 1
小于 -1 这个方法本来就是返回0 或1或-1 所以可以用上面的来比较