嵌套接口:Cast IDictionary< TKey,IList< TValue>到IDictionary< TKey,IEnumerable< TValue>>? [英] Nested Interfaces: Cast IDictionary<TKey, IList<TValue>> to IDictionary<TKey, IEnumerable<TValue>>?
问题描述
我认为将 IDictionary
IDictionary< TKey,IEnumerable& TValue>>
,但
I would think it's fairly straightforward to cast an IDictionary<TKey, IList<TValue>>
object to an IDictionary<TKey, IEnumerable<TValue>>
, but
var val = (IDictionary<TKey, IEnumerable<TValue>>)Value;
引发 System.InvalidCastException
/ p>
throws a System.InvalidCastException
, and
var val = Value as IDictionary<TKey, IEnumerable<TValue>>;
使 val
推荐答案
我认为这是很容易的。
IDictionary
对> IDictionary< TKey,IEnumerable< TValue>< / code& / p>
I would think it's fairly straightforward to cast an
IDictionary<TKey, IList<TValue>>
object to anIDictionary<TKey, IEnumerable<TValue>>
绝对不是。它不会是类型安全的。下面是一个为什么不是的例子:
Absolutely not. It wouldn't be type-safe. Here's an example of why not:
// This is fine...
IDictionary<string, IList<int>> dictionary = new Dictionary<string, IList<int>>();
// Suppose this were valid...
IDictionary<string, IEnumerable<int>> badDictionary = dictionary;
// LinkedList<T> doesn't implement IList<T>
badDictionary["foo"] = new LinkedList<int>();
// What should happen now?
IList<int> bang = dictionary["foo"];
正如你所看到的,这将导致问题 - 我们试图得到一个<$当我们期望所有的值都实现 IList< int>
时,c $ c> LinkedList< int> 泛型的要点是类型安全 - 那么你期望哪一行会失败?第一,第三和第四行看起来非常清楚对我有用 - 所以第二个是只有一个可能无法编译,它... ...
As you can see, that's going to cause problems - we'd be trying to get a LinkedList<int>
out when we expect all the values to implement IList<int>
. The point of generics is to be type-safe - so which line would you expect to fail? The first, third and fourth lines look pretty clearly valid to me - so the second one is the only one which can fail to compile, and it does...
现在在一些例子中,它可以安全地完成。例如,您可以将 IEnumerable
转换为 IEnumerable< object>
c $ c> IEnumerable< T> 只在输出位置使用 T
。
Now in some cases, it can be done safely. For example, you can convert (in C# 4) from IEnumerable<string>
to IEnumerable<object>
because IEnumerable<T>
only uses T
in "output" positions.
有关详情,请参见 MSDN 。
编辑:只是为了澄清 - 很容易用现有键/值对的副本创建一个新的字典,例如:使用连结:
Just to clarify - it's easy to create a new dictionary with a copy of the existing key/value pairs, e.g. using link:
var copy = original.ToDictionary<TKey, IEnumerable<TValue>>(pair => pair.Key,
pair => pair.Value);
您只需要知道您现在有两个单独的字典。
You just need to be aware that you now have two separate dictionaries.
这篇关于嵌套接口:Cast IDictionary< TKey,IList< TValue>到IDictionary< TKey,IEnumerable< TValue>>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!