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

IComparable<Student>是Student的父类,所以IComparable<Student>可以接收Student。
但是在使用CompareTo方法的时候,必须传入Student,不允许传入父类IComparable<Student>。
public interface IComparable<in T>, in关键字表示逆变ContravarianceEnables 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);
        }
    }
复制代码

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(403)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-01-31 Build website project by roslyn through devenv.com
2018-01-31 Configure environment variables for different tools in jenkins
点击右上角即可分享
微信分享提示