现在的位置: 首页 > 综合 > 正文

C#中IComparable泛型接口

2012年08月15日 ⁄ 综合 ⁄ 共 1360字 ⁄ 字号 评论关闭

    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);
            }

抱歉!评论已关闭.