简体   繁体   English

IComparable不需要逆变吗?

[英]IComparable doesn't need to be contravariant?

In the code below i am targetting the .NET 2.0 Framework. 在下面的代码中,我的目标是.NET 2.0 Framework。

I can pass a Programmer (derived) object to the Compare method which expects a Person (base class) 我可以将一个Programmer(派生)对象传递给需要Person(基类)的Compare方法

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' :) 但是,由于程序员是一个人(简单的OO概念),我声称在.NET 4.0中,IComparable接口声明中的'in'关键字是'矫枉过正':)

Before i write an email to Microsoft about them removing the in keyword please try to convince me otherwise :) 在我给微软写一封关于他们删除in关键字的电子邮件之前请尝试说服我:)

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: in以下代码中是合法的:

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

Without the in it would be illegal. 如果没有in这将是非法的。

By the Liskov substitution principle , if an IComparer<> implementation can compare Person instances, then it can compare objects of types derived from Person . 通过Liskov替换原则 ,如果IComparer<>实现可以比较Person实例,那么它可以比较从Person派生的类型的对象。 The in keyword allows you to use an IComparer<Person> comparer to compare objects of type MyPerson (derived from Person ). in关键字允许您使用IComparer<Person> MyPerson来比较MyPerson类型的MyPerson (派生自Person )。 An example use case is a comparer that orders Person instances by name for use in a SortedList<Person> ; 示例用例是一个比较器,它按名称对Person实例进行排序,以便在SortedList<Person> ; where the contravariant interface also allows the same comparer to be used with SortedList<MyPerson> . 逆变接口也允许相同的比较器与SortedList<MyPerson>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM