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

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.

原文地址:https://www.cnblogs.com/chucklu/p/13755756.html