一、接口(interface)
1.接口可多实现
2.实现方法与继承类相同
3.默认public,方法前不能加访问修饰符
public class Student:IComparable
{ }
//如果类继承了父类
public class Student:Person,IComparable
{ }
二、IComparable接口
List中如果放的是一个对象,如果对List进行排序的话,会报错,不知道通过那个字段进行排序。
解决方法:
例:在Student类中实现 IComparable 接口,并且实现CompareTo( object obj )方法
public class Student:Person,IComparable{
private string name;
private int age;
public Student(string name,int age)
{
this.name = name;
this.age = age;
}
public int CompareTo(object obj)
{
if(!(obj is Student))//判断是不是Student对象
{
throw new Exception("只能跟Student对象进行比较");
}
else
{
Student other = obj as Student;
return this.age.CompareTo(other.age);//根据年龄age排序
}
}
}
三、泛型接口
使用泛型接口,不需要进行类型判断与转换
public class Student:Person,IComparable<Student> {
private string name;
private int age;
public Student(string name,int age)
{
this.name = name;
this.age = age;
}
public int CompareTo(Student obj)
{
return this.age.CompareTo(other.age);//根据年龄age排序
}
}