Net Core教程

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

  

这篇关于C# IComparable 与 IComparer<T>的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!