gpt4 book ai didi

c# - C# 数组的协变和逆变

转载 作者:太空狗 更新时间:2023-10-29 20:52:58 24 4
gpt4 key购买 nike

<分区>

在阅读 section 时在维基百科上的一篇关于协变和逆变的文章中,我遇到了以下加粗的句子:

First consider the array type constructor: from the type Animal we can make the type Animal[] ("array of animals"). Should we treat this as

  • Covariant: a Cat[] is a Animal[]
  • Contravariant: a Animal[] is a Cat[]
  • 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 a Cat[], since a client reading from the array will expect a Cat, but an Animal[] may contain e.g. a Dog. So the contravariant rule is not safe.

Conversely, a Cat[] can not be treated as a Animal[]. It should always be possible to put a Dog into 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.

我理解这个概念;我只想要一个示例,说明如何在 C# 中“不能保证安全”。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com