zoukankan      html  css  js  c++  java
  • 协变和逆变基础概念的误解

    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.

  • 相关阅读:
    koa mog
    sdl
    基于WindowImplBase 更简单 以及 可变大小的,才是标准的
    df
    ffplay vc
    开源1bo
    react学习前一部分
    0514 react路由
    nodejs 调用进程
    Ubuntu Linux, 不要弄什么 wine,龙井 或者什么等 QQ 了。
  • 原文地址:https://www.cnblogs.com/chucklu/p/13755756.html
Copyright © 2011-2022 走看看