泛型接口

一.系统提供了许多泛型类和泛型接口,List<T>和Dictionary<K,V>是常用的泛型类。 IComparable<T>是最常用的泛型接口.

二.IComparable和IComparer接口区别:

1.IComparable在要比较的对象的类中实现,可以比较该对象和另一个对象;
2.IComparer在一个单独的类中实现,可以比较任意两个对象。

如下示例可以看出它们之间的区别:

1.实现IComparable接口代码:

public class Student: IComparable
{
private string name;
public string Name
{
   get
   {
    return name;
   }
   set
   {
    name = value;
   }
}
private int age;
public int Age
{
   get
   {
    return age;
   }
   set
   {
    age = value;
   }
}

//构造函数
public Student(string sname, int sage)
{
   this.name = sname;
   this.age = sage;
}
//实现接口中的方法
public int CompareTo(object obj)
{
   //这里需要将参数转化为Student对象

   Student other = obj as Student;
   //比较大小,返回结果
   return this.age.CompareTo(other.age);
}
}

.实现
class Progarm
{
static void Main()
{
   Student stu1 = new Student("张三", 10);
   Student stu2= new Student("李四", 20);
   Student stu3 = new Student("王五", 30);
   //对象之间进行比较
   if (stu1.CompareTo(stu2) > 0)
    Console.WriteLine("{0}的年龄大于{1}", stu1.Name, stu2.Name);
   else
    Console.WriteLine("{0}的年龄小于{1}", stu1.Name, stu2.Name);
}
}

 

2.实现IComparable<T>接口代码,把以上示例中实现接口方法改为下面的代码:

public int CompareTo(Student str){//实现接口中的方法

return this.age.CompareTo(str.age);//比较大小,返回结果,这里不需要不参数转换为Student对象。

}

 

posted @ 2013-06-29 22:19  LXJ5  阅读(272)  评论(0编辑  收藏  举报