协变和逆变基础概念的误解

IComparable doesn't need to be contravariant?

In the code below i am targetting the .NET 2.0 Framework.

I can pass a Programmer (derived) object to the Compare method which expects a Person (base class)

But since a Programmer IS A Person (simple OO concept) i claim that in .NET 4.0 the 'in' keyword in the IComparable interface declaration is 'overkill' :)

Before i write an email to Microsoft about them removing the in keyword please try to convince me otherwise :)

class Program
{
    static void Main(string[] args)
    {
        var person = new Person();

        var test = person.CompareTo(new Programmer());
    }
}

internal class Person : IComparable<Person>
{
    public int Id { get; set; }
    public string Name { get; set; }

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

class Programmer : Person
{
    public string ProgrammingLanguage { get; set; }
}

 

回答

Co- and contravariance is not about the types you pass into the methods. It is about the generic interfaces that contain the methods.

With in the following code is legal:

IComparable<Person> foo = ...;
IComparable<Programmer> bar = foo;

Without the in it would be illegal.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(155)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-09-30 炉石传说 古墓惊魂 灾祸领主 英雄技能
2016-09-30 你必须知道的EF知识和经验
2016-09-30 XUnit的使用
2016-09-30 如何使用NUnit
2015-09-30 C#中的Marshal
点击右上角即可分享
微信分享提示