且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#类型转换:显式类型转换存在,但会抛出一个转换错误?

更新时间:2023-02-13 09:28:56

它不工作的原因是,在的IDictionary&LT的价值; 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>());

您会想加入列表&LT; T&GT; 会的工作,因为这将编译给定的值类型是所谓的IEnumerable&LT; T&GT; 。它不能成功,不过,作为的实际的值类型为的HashSet&LT; T&GT;

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