2010-06-12 62 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的 是逆變

相關問題