【发布时间】:2015-05-19 03:02:20
【问题描述】:
我正在阅读 Jon Skeet 的深度 C#。虽然我已经理解了 CoVariance 和 ContraVariance 的概念,但是我无法理解这一行:
好吧,当 SomeType 只描述以下操作时,协方差是安全的 返回类型参数——当 SomeType 时逆变是安全的 只描述接受类型参数的操作。
有人可以用一个例子来解释一下,为什么两者在一个方向上都是安全的,而在另一个方向上不安全?
更新问题:
从给出的答案中我仍然不明白。我将尝试使用书中相同的示例来解释我的担忧 - C# In Depth。
它使用以下类层次结构进行解释:
协方差是:尝试从IEnumerable<Circle> 转换为IEnumerable<IShape>,但有人提到,这种转换只有在我们从某个方法返回时执行时才是类型安全的,而当我们将其传递为时不是类型安全的一个 IN 参数。
IEnumerable<IShape> GetShapes()
{
IEnumerable<Circle> circles = GetEnumerableOfCircles();
return circles; // Conversion from IEnumerable<Circle> to IEnumerable<IShape> - COVARIANCE
}
void SomeMethod()
{
IEnumerable<Circle> circles = GetEnumerableOfCircles();
DoSomethingWithShapes(circles); // Conversion from IEnumerable<Circle> to IEnumerable<IShape> - COVARIANCE
}
void DoSomethingWithShapes(IEnumerable<IShape> shapes) // Why this COVARIANCE is type unsafe??
{
// do something with Shapes
}
CONTRA VARIANCE 是:尝试从IEnumerable<IShape> 转换为IEnumerable<Circle>,仅在将其作为IN 参数发送时才提到它是类型安全的。
IEnumerable<Circle> GetShapes()
{
IEnumerable<IShape> shapes = GetEnumerableOfIShapes();
return shapes; // Conversion from IEnumerable<IShape> to IEnumerable<Circle> - Contra-Variance
// Why this Contra-Variance is type unsafe??
}
void SomeMethod()
{
IEnumerable<IShape> shapes = GetEnumerableOfIShapes();
DoSomethingWithCircles(shapes); // Conversion from IEnumerable<IShape> to IEnumerable<Circle> - Contra-Variance
}
void DoSomethingWithCircles(IEnumerable<Circle> circles)
{
// do something with Circles
}
【问题讨论】:
-
您能否具体说明您对所提供答案的不理解之处,以便可以改进它们?它们相当详细,因此您对什么感到困惑并不是很明显。
-
这两个问题在试图解释同一个概念的方式上是相关的。但它们只是相关的,并不完全相同。
标签: c#