【发布时间】:2016-11-24 23:48:14
【问题描述】:
我了解到HashSet 实现了IEnumerable 接口。因此,可以将HashSet 对象隐式转换为IEnumerable:
HashSet<T> foo = new HashSet<T>();
IEnumerable<T> foo2 = foo; // Implicit cast, everything fine.
这也适用于嵌套的泛型类型:
HashSet<HashSet<T>> dong = new HashSet<HashSet<T>>();
IEnumerable<IEnumerable<T>> dong2 = dong; // Implicit cast, everything fine.
至少我是这么认为的。但是如果我发Dictionary,就会遇到问题:
IDictionary<T, HashSet<T>> bar = new Dictionary<T, HashSet<T>>();
IDictionary<T, IEnumerable<T>> bar2 = bar; // compile error
最后一行给了我以下编译错误(Visual Studio 2015):
不能隐式转换类型
System.Collections.Generic.IDictionary<T, System.Collections.Generic.HashSet<T>>到System.Collections.Generic.IDictionary<T, System.Collections.Generic.IEnumerable<T>>.存在显式转换(您是否缺少演员表?)
但是如果我通过写作来进行演员表
IDictionary<T, IEnumerable<T>> bar2 = (IDictionary<T, IEnumerable<T>>) bar;
然后我在运行时得到一个无效的强制转换异常。
两个问题:
- 我该如何解决这个问题?是唯一的方法来迭代键并一点一点地建立一个新的字典吗?
- 为什么我首先会遇到这个问题,即使
HashSet确实实现了IEnumerable接口?
【问题讨论】:
-
IEnumerable<T>是 covariant。IDictionary<TKey,TValue>不是。 外部类型很重要
标签: c# dictionary type-conversion ienumerable hashset