2010-06-12 105 views
1

为什么DoesntWork()以下工作?错误是: Cannot implicitly convert type 'List' to 'IEnumerable'. An explicit conversion exists (are you missing a cast?)。我知道这是关于通用/模板的东西我没有得到,但列表是IEnumerable和实施者 IInterface。我不明白为什么这需要被铸造(或如果它真的可以)。容器<ImplementerOfIInterface>不是容器<IInterface>。为什么不?

public interface IInterface 
{ 
    // ... 
} 

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

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

回答

4

它与covariance有关。这里有一个很好的博客post。如果您不使用4.0,则必须使用System.Linq Cast方法来施放该列表。

2

这适用于网4.0: 公共IEnumerable接口< T>:IEnumerable的 是逆变

相关问题