更新时间:2023-02-13 09:37:44
它不起作用的原因是 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
。
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());