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.

  • 相关阅读:
    C++结构体中sizeof
    sizeof()的用法
    XStream和Json
    省市联动
    ajax
    配置文件的读取
    JSP标签库
    字符串函数参数传入传出(去空格)
    字符串函数参数传入传出(字符串反转)
    opendir,readdir,closedir
  • 原文地址:https://www.cnblogs.com/chucklu/p/13755756.html
Copyright © 2011-2022 走看看