为什么字典不能转换为 IEnumerable

Why cannot a dictionary convert to an IEnumerable

考虑:

public IReadOnlyDictionary<Object, IEnumerable<Object>> readOnlyDictionary
{
    get { return dictionary;}
}

private Dictionary<Object, List<Object>> dictionary;

产生错误:

Error CS0266
Cannot implicitly convert type 'System.Collections.Generic.Dictionary<object,System.Collections.Generic.List>' to 'System.Collections.Generic.IReadOnlyDictionary<object, System.Collections.Generic.IEnumerable>'. An explicit conversion exists (are you missing a cast?)

List<Object> 实现 IEnumerable,并且从 List 返回 IEnumerable 工作正常。为什么在 Dictionary 之类的容器中会失败?

List<T> 实现了 IEnumerable<T>,但 Dictionary<Object, List<Object>> 不是 Dictionary<Object, IEnumerable<Object>>。这根本行不通。您必须将 return 类型更改为 IReadOnlyDictionary<Object, List<Object>> 或将字典类型更改为 Dictionary<Object, IEnumerable<Object>>.

无耻地复制粘贴 GSerg 和 Olivier 的好链接:

  • Ok, i got, but wth is covariant?