[英]Why does upcasting IDictionary<TKey, TValue> to IEnumerable<object> fail?
See the following code snippet: 请参阅以下代码段:
(IEnumerable<object>)new Dictionary<string, string>()
The above cast will throw an invalid cast exception. 上面的强制转换将抛出无效的强制转换异常。
Actually, IDictionary<TKey, TValue>
also indirectly implements IEnumerable<out T>
, because it also implements ICollection<T>
. 实际上,
IDictionary<TKey, TValue>
也间接实现了IEnumerable<out T>
,因为它还实现了ICollection<T>
。 That is, the whole cast should be valid. 也就是说,整个演员应该是有效的。
In fact, for me it is even more strange that if I run the whole cast on a debugger watch slot, it works ! 事实上,对我来说更奇怪的是,如果我在调试器手表插槽上运行整个演员, 它就可以了 !
What's going on? 这是怎么回事?
That dictionary does implement IEnumerable<KeyValuePair<TKey, TValue>>
and IEnumerable
, but IEnumerable
of a struct is not the same as IEnumerable
of an object. 该字典确实实现
IEnumerable<KeyValuePair<TKey, TValue>>
和IEnumerable
,但IEnumerable
一个结构是不一样IEnumerable
的一个对象。 Variance only works for reference-types . 方差仅适用于参考类型 。
This does work at my end and should be the logical choice: 这确实在我的最终工作,应该是合乎逻辑的选择:
var x = (IEnumerable)new Dictionary<string, string>();
As a sample, this does work: 作为一个示例,这确实有效:
List<string> l = new List<string>();
var x = (IEnumerable<object>)l;
But this one doesn't: 但是这个没有:
List<DateTime> l2 = new List<DateTime>();
var x = (IEnumerable<object>)l2;
Clearly indicating the struct is the problem. 清楚地表明结构是问题。
(Why it works in your Watch windows, I don't know) (为什么它在你的Watch窗口中工作,我不知道)
I think this is because KeyValuePair
is a Value-Type. 我认为这是因为
KeyValuePair
是一个Value-Type。
This would fail: 这会失败:
List<int> ints = new List<int>();
var objs = (IEnumerable<object>)ints;
This would work: 这可行:
List<string> ints = new List<string>();
var objs = (IEnumerable<object>)ints;
same goes for the dictionary. 字典也一样。
如果你真的不能使用普通的IEnumerable
,试试这个:
new Dictionary<string, string>().Cast<object>();
This is strange. 这很奇怪。 Your code snippet works fine with .NET 4.0.
您的代码片段适用于.NET 4.0。 I suggest you cast to
IEnumerable
. 我建议你施放到
IEnumerable
。
Read: IDictionary Interface (MSDN) 阅读: IDictionary接口 (MSDN)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.