【问题标题】:How is IEnumerable<T> Contra-variant?IEnumerable<T> 如何反变?
【发布时间】:2010-07-11 01:03:08
【问题描述】:

这篇文章 (http://blogs.msdn.com/b/brada/archive/2005/01/18/355755.aspx) 说 IEnumerable&lt;T&gt; 是反变体。然而类型 T 是协变的,因为它是一个 out 参数。那么在什么情况下IEnumerable&lt;T&gt; 反变体?

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

【问题讨论】:

    标签: c# generics ienumerable covariance contravariance


    【解决方案1】:

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

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

    类型参数

    出来了

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

    从这个post 我们得到:

    基类库已更新以支持协方差和 各种常见的逆变 使用的接口。例如, IEnumerable 现在是协变的 接口 - 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

    【讨论】:

    • 更重要的是:问题中引用的博客条目不正确。作者混淆了协变和逆变。这很容易做到,IMO...
    • 没错。布拉德在帖子中自相矛盾。
    • 我就是这么想的。但是,由于博客文章提到它来自 Anders - C# 架构师和 Guru,我对此表示怀疑!感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    相关资源
    最近更新 更多