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

C#中IComparable泛型接口

2008-09-08 16:47 561 查看
public class Student : IComparable<Student>

{

private String name;

private int age;

public Student(string _name, int _age)

{

name = _name;

age = _age;

}

public String Name

{

get

{

return this.name;

}

set

{

this.name = value;

}

}

public int Age

{

get

{

return this.age;

}

set

{

this.age = value;

}

}

public override string ToString()

{

return string.Format("{0},{1}",this.name,this.age);

}

#region IComparable 成员

public int CompareTo(Student other)

{

return this.age.CompareTo(other.age);

}

#endregion

}

//Main里调用

Student son = new Student("Son", 23);

Student tom = new Student("Tom", 45);

Student anle = new Student("Anle", 32);

List<Student> list = new List<Student>();

list.Add(son);

list.Add(tom);

list.Add(anle);

Console.WriteLine("-----排序前-----");

foreach (Student s in list)

{

Console.WriteLine(s);

}

list.Sort();

Console.WriteLine("-----排序后-----");

foreach (Student s in list)

{

Console.WriteLine(s);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: