<span style="font-size:18px;">class Person :IComparable</span>
<span style="font-size:18px;">{
public int Age;
public string Name;
public Person(int age,string name)
{
this.Age = age;
this.Name = name;
}
public int CompareTo(object obj)
{
if (obj is Person)
{
return this.Age - (obj as Person).Age;
}
else
{
throw new ArgumentException("type error");
}
}
}</span>
<span style="font-size:18px;">
</span>
<pre name="code" class="csharp"><span style="font-size:18px;">class ComparePerson:IComparer
{
public static IComparer Default = new ComparePerson();
int IComparer.Compare(object x, object y)
{
if ((x is Person) && (y is Person))
{
return Comparer.Default.Compare(((Person)x).Name, ((Person)y).Name);
}
else
{
throw new ArgumentException("typer error");
}
}
}</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">
</span>
<span style="font-size:14px;">class Program
{
static void Main(string[] args)
{
ArrayList Persons = new ArrayList();
Persons.Add(new Person(30, "Jim"));
Persons.Add(new Person(25, "Bob"));
Persons.Add(new Person(27, "Bert"));
Persons.Add(new Person(22, "Ernie"));
for(int i=0;i<Persons.Count;i++)
{
Console.WriteLine("{0},({1})", ((Person)Persons[i]).Name, ((Person)Persons[i]).Age);
}
Console.WriteLine();
Console.WriteLine("age:-----------------------");
Persons.Sort(); 默认的排序方式是调用了实现Icomparable接口的Person类中的CompareTo方法
for (int i = 0; i < Persons.Count; i++)
{
Console.WriteLine("{0},({1})", ((Person)Persons[i]).Name, ((Person)Persons[i]).Age);
}
Console.WriteLine();
Console.WriteLine("name:-----------------------");
Persons.Sort(ComparePerson.Default); /非默认排序使用了实现IComparer的ComparePerson类 类中有一个公共静态字段以方便使用public static IComparer Default = new ComparePerson();
for (int i = 0; i < Persons.Count; i++)
{
Console.WriteLine("{0},({1})", ((Person)Persons[i]).Name, ((Person)Persons[i]).Age);
}
Console.ReadKey();
}
}</span>