首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

IComparable接口示范代码

2013-10-29 
IComparable接口示例代码定义学生类,该类实现IComparable接口的CompareTo方法,该方法对Age 进行大小比较。p

IComparable接口示例代码

定义学生类,该类实现IComparable接口的CompareTo方法,该方法对Age 进行大小比较。

public class Student:IComparable{    public string Name { get; set; }    public string Sex { get; set; }    public int Age { get; set; }    public int CompareTo(object obj)    {        Student stu = obj as Student;        if (Age > stu.Age)        {            return 1;        }        else if (Age == stu.Age)        {            return 0;        }        else        {            return -1;        }    }}

调用List<T>.Sort方法实现stuList按照学生的年龄来排序。

static void Main(string[] args){     List<Student> stuList = new List<Student>();     stuList.Add(new Student() { Name = "tiana0", Sex = "Man", Age = 18 });     stuList.Add(new Student() { Name = "tiana1", Sex = "Woman", Age = 20 });     stuList.Add(new Student() { Name = "tiana2", Sex = "Woman", Age = 16 });     stuList.Add(new Student() { Name = "tiana3", Sex = "Man", Age = 21 });     stuList.Add(new Student() { Name = "tiana4", Sex = "Woman", Age = 19 });     stuList.Sort();     foreach (Student stu in stuList)     {          Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age);     }}

代码运行结果如下:

IComparable接口示范代码

 

 

 

热点排行