gpt4 book ai didi

c# - 协方差是关于接受值吗?

转载 作者:行者123 更新时间:2023-12-04 10:50:01 25 4
gpt4 key购买 nike

协方差是关于接受值吗?

我正在通过 学习 C# CLR 通过 C# 书。我遇到了以下摘录:

Since T is covariant, it is possible to have the following code compile and run successfully:


// This method accepts an IEnumerable of any reference type
Int32 Count(IEnumerable<Object> collection) { ... }

...
// The call below passes an IEnumerable<String> to Count
Int32 c = Count(new[] { "Grant" });

我在这里很困惑。因为协方差是关于具有所需类型的基本类型之一的类型。因此,协方差仅在返回类型的上下文中使用。而在上面的例子中,我们有一个 String (源自 Object ,因此是逆变的,但不是协变的),它用于传递参数(但不返回值)的上下文中。

那么,我们应该在上面的例子中使用逆变而不是协变(意思是书中有错误)?

更新

在评论之后,我得到了另一个问题。以下定义是否正确?

Contravariant Meaning that the generic type parameter can change from a class to a class derived from it. In C#, you indicate contravariant generic type parameters with the in keyword. Contravariant generic type parameters can appear only in input positions such as a method’s argument.

Covariant Meaning that the generic type argument can change from a class to one of its base classes. In C#, you indicate covariant generic type parameters with the out keyword. Covariant

最佳答案

正如乔希指出的那样,这本书是正确的。
您可以查看 this link如果您想从其他来源确认。

IEnumerable<Cat> is a subtype of IEnumerable<Animal>. The subtyping is preserved because IEnumerable<T> is covariant on T.


C# 中用于这些概念的两个关键字是 out用于协变和 in为逆变。在 IEnumerable<T>案例这转化为 IEnumerable<out T> .
希望这可以帮助。
更新
您必须按如下方式反转您的定义。

Covariant Meaning that the generic type parameter can be a certain class and all the derived classes from it (IEnumerable<Object> can be a IEnumerable<String> since String is a subtype of Object). In C#, you indicate covariant generic type parameters with the out keyword.

Contravariant Meaning that the generic type argument can change from aclass to one of its base classes. In C#, you indicate contravariantgeneric type parameters with the in keyword.

关于c# - 协方差是关于接受值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59533159/

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