更新时间:2023-02-13 09:28:56
它不工作的原因是,在的IDictionary<的价值; TKEY的,TValue>
不是的共变的(并且也不是关键,出于同样的原因)。如果它被允许存在,那么这段代码编译,但的具有的导致异常:
The reason it doesn't work is that the value in IDictionary<TKey, TValue>
is not co-variant (and nor is the key, for the same reasons). If it were allowed to be, then this code would compile, but has to result in an exception:
IDictionary<T, HashSet<T>> foo = new Dictionary<T, HashSet<T>>();
IDictionary<T, IEnumerable<T>> bar = foo;
foo.Add(key, new List<T>());
您会想加入列表< T>
会的工作,因为这将编译给定的值类型是所谓的IEnumerable< T>
。它不能成功,不过,作为的实际的值类型为的HashSet< T>
You'd think adding a List<T>
would work, as it would compile given the value type is supposedly IEnumerable<T>
. It can't succeed, though, as the actual value type is HashSet<T>
.
所以,是的。唯一的方法是创建一个新的字典
So, yes: the only way is to create a new dictionary.
var bar = foo.ToDictionary(x => x.Key, x => x.Value.AsEnumerable());