编程语言
首页 > 编程语言> > C# IComparable 与 IComparer<T>

C# IComparable 与 IComparer<T>

作者:互联网

//IComparable的排序使用
public class Student : IComparable
{
    private string name;
    
    private int age;
    
    public string Name
    {
        get { return name; }
    }

    public int Age
    {
        get { return age; }
    }

    public Student() { }

    public Student(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public override string ToString()
    {
        return $"姓名:{this.name}     年龄:{this.age}";
    }

    public int CompareTo(object obj)
    {
        Student student = obj as Student;
        if (this.age == student.Age)
        {
            return 0;
        }
        else if(this.age > student.Age)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }
    
    //调用方法  但存在拆箱装箱
    // List<Student> studentsList = new List<Student>()
    // {
    //     new Student("a", 14),
    //     new Student("b", 13),
    //     new Student("c", 12),
    //     new Student("d", 11),
    //     new Student("e", 10),
    // };
    // studentsList.Sort();
    
    //下面我们使用IComparer<T> 实现对一个构造类的排序 不存在拆箱装箱

    public class StudentSort : IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
            return x.age.CompareTo(y.age);
        }
    }

    //调用方式
    // List<Student> studentsList = new List<Student>()
    // {
    //     new Student("a", 14),
    //     new Student("b", 13),
    //     new Student("c", 12),
    //     new Student("d", 11),
    //     new Student("e", 10),
    // };
    // studentsList.Sort(new Student.StudentSort());

  

标签:IComparer,return,IComparable,C#,age,Student,new,public,name
来源: https://www.cnblogs.com/zjp959/p/15966081.html