IEnumerable< T>相反? [英] How is IEnumerable<T> Contra-variant?

查看:99
本文介绍了IEnumerable< T>相反?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此帖子( http:// blogs。 msdn.com/b/brada/archive/2005/01/18/355755.aspx )说, IEnumerable< T> 是对立的。但是类型T是协变的,因为它是 out 参数。那么 IEnumerable< T> 是什么?

This post (http://blogs.msdn.com/b/brada/archive/2005/01/18/355755.aspx) says IEnumerable<T> is Contra-variant. However type T is co-variant because it is an out parameter. So in what context is IEnumerable<T> Contra-variant ??

希望我不会感到困惑!

Hope I am not confusing! Thanks for the answers in advance!

推荐答案

IEnumerable不是反变量。它是协变的。

IEnumerable isn't contra-variant. It's covariant.

来自MSDN (IEnumerable<(Of<(T>)>)接口),我们有:

From MSDN (IEnumerable<(Of <(T>)>) Interface) we have that:


类型参数

Type Parameters

out T

要枚举的对象类型。
此类型参数是协变的。也就是说,您可以使用指定的
类型,也可以使用派生出更多
的任何类型。

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

通过此帖子,我们得到了:

基类库已更新,以支持各种常用的
接口中的协方差和
协变。例如,
IEnumerable现在成为协变量
接口
– IEnumerable。

The Base Class Library has been updated to support covariance and contravariance in various commonly used interfaces. For example, IEnumerable is now a covariant interface – 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); 
}

有关更多示例,请查看:

For more examples on this, take a look at:

协方差和协方差常见问题解答

C#中的协方差和对比度,第一部分(Eric Lippert撰写的有关协方差和对比度的大量文章)

Covariance and Contravariance in C#, Part One (Great series of posts by Eric Lippert about Covariance And Contravariance)

了解C#协方差和反方差(3)样本

这篇关于IEnumerable&lt; T&gt;相反?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆