问题描述
概念协方差和逆变的含义是什么?
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:
此外,你说类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.
这篇关于关于类继承的协方差与逆变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!