【问题标题】:Container<ImplementerOfIInterface> is not Container<IInterface>. Why not?Container<ImplementerOfIInterface> 不是 Container<IInterface>。为什么不?
【发布时间】:2010-06-12 14:05:56
【问题描述】:

为什么DoesntWork() 不能在下面工作?错误是: Cannot implicitly convert type 'List' to 'IEnumerable'. An explicit conversion exists (are you missing a cast?)。我知道这是关于我没有得到的通用/模板的东西,但 List 是 IEnumerable 并且实施者 是一个 IInterface。我不明白为什么需要强制转换(或者如果真的可以)。

public interface IInterface
{
    // ...
}

public class Implementer : IInterface
{
    // ...
}

IEnumerable<IInterface> DoesntWork()
{
    List<Implementer> result = new List<Implementer>();
    return result;
}

【问题讨论】:

    标签: c# inheritance interface


    【解决方案1】:

    它与covariance 有关。这是一个不错的博客post。如果您不使用 4.0,则必须使用 System.Linq Cast 方法强制转换列表。

    【讨论】:

      【解决方案2】:

      这适用于 Net 4.0: 公共接口 IEnumerableout T> : IEnumerable out 是逆变的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        • 2014-04-11
        • 2020-11-08
        • 1970-01-01
        • 2019-09-07
        相关资源
        最近更新 更多