gpt4 book ai didi

c# - IEnumerable 是如何反变的?

转载 作者:太空狗 更新时间:2023-10-30 00:28:22 26 4
gpt4 key购买 nike

这篇文章 ( http://blogs.msdn.com/b/brada/archive/2005/01/18/355755.aspx ) 说 IEnumerable<T>是逆变的。但是类型 T 是协变的,因为它是 out范围。那么在什么情况下是IEnumerable<T>逆变 ??

希望我没有混淆!提前感谢您的回答!

最佳答案

IEnumerable 不是逆变的。它是协变的。

来自 MSDN (IEnumerable<(Of <(T>)>) Interface)我们有:

Type Parameters

out T

The type of objects to enumerate.This type parameter is covariant. That is, you can use either the typeyou specified or any type that is morederived.

从这里post我们有:

The Base Class Library has been updated to support covariance andcontravariance in various commonlyused interfaces. For example,IEnumerable is now a covariantinterface – IEnumerable.

示例代码:

// Covariant parameters can be used as result types
interface IEnumerator<out T>
{
T Current { get; }

bool MoveNext();
}

// Covariant parameters can be used in covariant result types
interface IEnumerable<out T>
{
IEnumerator<T> GetEnumerator();
}

// Contravariant parameters can be used as argument types
interface IComparer<in T>
{
bool Compare(T x, T y);
}

有关这方面的更多示例,请查看:

Covariance and Contravariance FAQ

Covariance and Contravariance in C#, Part One (Eric Lippert 关于协变和逆变的精彩系列文章)

Understanding C# Covariance And Contravariance (3) Samples

关于c# - IEnumerable<T> 是如何反变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221452/

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