First consider the array type constructor: from the type
Animalwe can make the type
Animal(“array of animals”). Should we treat this as
- Covariant: a
- Contravariant: a
- 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
Animalcan be treated as if it were a
Cat, since a client reading from the array will expect a Cat, but an
Animalmay contain e.g. a
Dog. So the contravariant rule is not safe.
Catcan not be treated as a
Animal. It should always be possible to put a
Animal. 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.
string strings = new string; object objects = strings; objects = new object();
> One by me关于使用通用包装的性能和安全性
> One on immutable arrays来自BCL团队
> Part 2 of Eric Lippert’s blog series on variance in general(该系列主要针对仿制药,但这部分是针对阵列的)