- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
<分区>
在阅读 section 时在维基百科上的一篇关于协变和逆变的文章中,我遇到了以下加粗的句子:
First consider the array type constructor: from the type
Animal
we can make the typeAnimal[]
("array of animals"). Should we treat this as
- Covariant: a
Cat[]
is aAnimal[]
- Contravariant: a
Animal[]
is aCat[]
- or neither (invariant)?
If we wish to avoid type errors, and the array supports both reading and writing elements, then only the third choice is safe. Clearly, not every
Animal[]
can be treated as if it were aCat[]
, since a client reading from the array will expect a Cat, but anAnimal[]
may contain e.g. aDog
. So the contravariant rule is not safe.Conversely, a
Cat[]
can not be treated as aAnimal[]
. It should always be possible to put aDog
into aAnimal[]
. With covariant arrays this can not be guaranteed to be safe, since the backing store might actually be an array of cats. So the covariant rule is also not safe—the array constructor should be invariant. Note that this is only a issue for mutable arrays; the covariant rule is safe for immutable (read-only) arrays.
我理解这个概念;我只想要一个示例,说明如何在 C# 中“不能保证安全”。
在我的设置中,我试图有一个界面 Table继承自 Map (因为它主要用作 map 的包装器)。两个类继承自 Table - 本地和全局。全局的将有一个可变的映射,而本地的将有一个只有本地条目的映射。
Rust Nomicon 有 an entire section on variance除了关于 Box 的这一小节,我或多或少地理解了这一点和 Vec在 T 上(共同)变体. Box and Vec
我是一名优秀的程序员,十分优秀!