您的位置:首页 > 编程语言 > C#

C#中IComparable接口和IComparer接口应用的实例

2012-03-15 14:23 525 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

using Ch11Exo5;

using Ch11Ex05;

namespace Ch11Exo5

{

class Person : IComparable //定义一个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) //判断obj是否是Person类型或Person类的继承类的类型

{

Person otherPerson = obj as Person; //把ojb转换为Person类型后赋给otherPerson

return this.Age - otherPerson.Age;

}

else

{

throw new ArgumentException("Object to compare to is not a Person object");

}

}

}

}

namespace Ch11Ex05 //定义一个PersonComparerName 类,继承系统定义的IComparer接口

{

public class PersonComparerName : IComparer

{

public static IComparer Default = new PersonComparerName();

public int 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("One or both objects to compare are not Person objects.");

}

}

}

}

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

ArrayList list = new ArrayList(); //定义一个ArrayList型对象list

list.Add(new Person("Jim", 30)); //想list中添加成员

list.Add(new Person("Bob", 25));

list.Add(new Person("Bert", 27));

list.Add(new Person("Ernie", 22));

Console.WriteLine("Unsored people");

for (int i = 0; i < list.Count; i++) //打印没有排序的list中的成员

{

Console.WriteLine("{0} {1}", (list[i] as Person).Name, (list[i] as Person).Age);

}

Console.WriteLine();

Console.WriteLine("people sorted with default comparer (by age)");

list.Sort(); //此处会调用Person类中CompareTo函数进行排序(即:进行默认的排序)

for (int i = 0; i < list.Count; i++) //打印通过Age进行排序的list中的成员

{

Console.WriteLine("{0} {1}", (list[i] as Person).Name, (list[i] as Person).Age);

}

Console.WriteLine();

Console.WriteLine("people sorted with nondefault comparer (by name)");

list.Sort(PersonComparerName.Default); //此处会调用PersonComparerName 类中Compare函数进行排序(即:按照指定的参数为依据进行排序)

for (int i = 0; i < list.Count; i++)//打印通过Name进行排序的list中的成员

{

Console.WriteLine("{0} {1}", (list[i] as Person).Name, (list[i] as Person).Age);

}

}

}

}

注解:

IComparable接口和IComparer接口的区别:

IComparable在要比较的对象的类中实现,可以比较该对象和另一个对象

IComparer在单独的一个类中实现,可以比较任意两个对象

这两个接口是.NET Framework中比较对象的标准方式

对于我们用ArrayList类对象来存储数据时,如果我们存储的是系统定义的基本数据类型,若我们想对存储的数据排序,我们不需要继承IComparable接口和IComparer接口,来实现接口中定义的成员,从而达到排序的目的,我们可以直接使用ArrayLis类中的sort成员函数就可以做到排序目的,但是对于ArrayList对象中存储的是我们自定义的类对象是,若想对其排序,那么在我们定义的类中继承IComparable接口或IComparer接口,实现接口中的成员(对于IComparable接口,要实现CompareTo函数,它带一个类型为object的参数;对于IComparer接口,要实现Compare函数,它带两个类型为object的参数),在用ArrayList类对象调用sort成员函数时会调用我们从接口中继承过来的在类中实现的函数,从而达到我们的排序目的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: