Student : IComparable<Student> 以及逆变和协变

IComparable<Student>是Student的父类,所以IComparable<Student>可以接收Student。
但是在使用CompareTo方法的时候,必须传入Student,不允许传入父类IComparable<Student>。
public interface IComparable<in T>
public class Student : IComparable<Student>
    {
        public int Id { get; set; }

        public int CompareTo(Student other)
        {
            return Id - other.Id;
        }
    }

    class Test
    {
        public Test()
        {
            IComparable<Student> student1 = new Student() {Id = 1};

            IComparable<Student> student2 = new Student() {Id = 2};
            int result = student1.CompareTo(student2);
        }
    }

猜你喜欢

转载自www.cnblogs.com/chucklu/p/10343915.html