关于类继承的协方差与逆变

关于类继承的协方差与逆变

问题描述:

概念协方差和逆变的含义是什么?

What is the meaning of the concepts 'covariance' and 'contravariance'?

给定2个类,动物 (继承自 Animal ),我的理解是,如果您尝试将大象放入动物数组,您会遇到运行时错误,这是因为Elephant是更大(更具体)。但你能把一个动物放入大象数组,看看大象是如何保证包含动物属性?

Given 2 classes, Animal and Elephant (which inherits from Animal), my understanding is that you would get a run-time errors if you try and put an Elephant into an array of Animals, and this happens because Elephant is "bigger" (more specific) than Animal. But could you place an Animal into an array of Elephant, seeing how Elephant is guaranteed to contain the Animal properties?

它向后。您可以将大象添加到动物数组,因为它是一个动物,它保证拥有动物所需的所有方法。您无法向Elephant数组添加动物,因为它拥有大象需要的所有方法。

You have it backwards. You can add an Elephant to an Animal array because it is an Animal, and it's guaranteed to have all of the methods an Animal is required to have. You can't add an Animal to an Elephant array because it does not have all of the methods that an Elephant is required to have.

有关协方差和逆向性的维基百科文章对此有很好的解释:

The Wikipedia article on covariance and contravariance has a good explanation of this:


在编程语言的类型系统中,从类型到类型的运算符是协变的,如果它保留类型的排序,从更具体的到更通用的;如果它颠倒这个排序是逆向的。如果这两者都不适用,则算子是不变的。这些术语来自类别理论。

Within the type system of a programming language, an operator from types to types is covariant if it preserves the ordering, ≤, of types, which orders types from more specific ones to more generic ones; it is contravariant if it reverses this ordering. If neither of these apply, the operator is invariant. These terms come from category theory.

此外,你说类Elephant是更大,而不是这样。类型动物是更大的意义,它包括更具体的类型,如大象,长颈鹿和狮子。

Also, you said that type Elephant was "bigger", and this is not the case. Type Animal is "bigger" in the sense that it includes more specific types, such as Elephant, Giraffe, and Lion.