C# type conversion: Explicit cast exists but throws a conversion error?

耗尽温柔 提交于 2019-12-06 06:27:51

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>());

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());

How do I solve this? Is the only way to iterate over the keys and build up a new dictionary bit by bit?

It may not be the most elegant solution, but it works:

IDictionary<T, HashSet<T>> bar = new Dictionary<T, HashSet<T>>();
IDictionary<T, IEnumerable<T>> bar2 = bar.ToDictionary(x => x.Key, y => (IEnumerable<T>)y.Value);

The reason why the Dictionary cast isn't working is because IEnumerable is co-variant, note <out T> in the declaration

public interface IEnumerable<out T> : IEnumerable

IDictionary isn't.

public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable

You can read more about it here: https://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!