我了解到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>>
to
System.Collections.Generic.IDictionary<T, System.Collections.Generic.IEnumerable<T>>
.
存在显式转换(您是否缺少强制转换?)
但如果我通过写作来选角
IDictionary<T, IEnumerable<T>> bar2 = (IDictionary<T, IEnumerable<T>>) bar;
然后我在运行时收到无效的强制转换异常。
两个问题:
- 我该如何解决这个问题?迭代键并一点一点建立新字典的唯一方法是吗?
- 为什么我首先会遇到这个问题,尽管
HashSet
确实实施了IEnumerable
界面?