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

IComparable<Student>是Student的父类,所以IComparable<Student>可以接收Student。
但是在使用CompareTo方法的时候,必须传入Student,不允许传入父类IComparable<Student>。
public interface IComparable<in T>, in关键字表示逆变Contravariance,Enables you to use a more generic (less derived) type than originally specified
  //Contravariance, Enables you to use a more generic (less derived) type than originally specified.  用来做函数参数
            //public delegate void Action<in T>(T obj)
            Action<Base> actionBase = ActionMethod;
            Action<Derived> actionDerived = actionBase;
            actionDerived(new Derived());

 

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

 

修改成下面的代码就可以了,使用var关键字,让编译自动推断类型

 [TestFixture]
    public class TestHelper
    {
        [Test]
        public void Test()
        {
            var student1 = new Student() { Id = 1 };

            var student2 = new Student() { Id = 2 };
            int result = student1.CompareTo(student2);
            Console.WriteLine(result);
        }
    }

 

posted @ 2019-01-31 20:21  ChuckLu  阅读(398)  评论(0编辑  收藏  举报