无法CAST()通用字典项的DictionaryEntry时,通过非一般的IDictionary枚举 [英] Unable to Cast() generic dictionary item to DictionaryEntry when enumerated via non-generic IDictionary

查看:136
本文介绍了无法CAST()通用字典项的DictionaryEntry时,通过非一般的IDictionary枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些code,它遍历一个非一般的 的IDictionary 通过先调用LINQ的 铸造 方法。路过即使我专门通过非泛型的IDictionary 接口,使​​用它的通用字典实现时,但我得到一个无效的转换异常。

I have some code that iterates over a non-generic IDictionary by first calling the LINQ Cast method. However I get an invalid cast exception when passing a generic dictionary implementation even though I'm specifically using it via the non-generic IDictionary interface.

IDictionary dict = new Dictionary<object, object> {{"test", "test"}};
foreach (var item in dict)
{
    Debug.Assert(item is DictionaryEntry); // works
}
dict.Cast<DictionaryEntry>().ToList();     // FAILS

为什么铸造法时,正常的循环没有上面的失败?有没有一种可靠的方法来转换非通用词典到的DictionaryEntry 枚举而不诉诸人工列表建设?

Why does the Cast method above fail when the normal iteration doesn't? Is there a reliable way to transform a non-generic dictionary into an enumeration of DictionaryEntry without resorting to manual list building?

推荐答案

问题是,在词典和其中的的IEnumerable 实施; TKEY的,TValue&GT; 列举KeyValuePairs。的foreach上的IDictionary 将使用 IDictionary.GetEnumerator 函数返回一个IDictionaryEnumerator(在内部,这告诉的IEnumerator 在内部枚举类返回哪种类型的功能。)鉴于演员函数操作的IEnumerable,这将使其返回一个KeyValuePair。

The problem is that the IEnumerable implementation on Dictionary<TKey,TValue> enumerates KeyValuePairs. Foreach on an IDictionary will use the IDictionary.GetEnumerator function which returns an IDictionaryEnumerator (internally, this tells the IEnumerator function on the internal Enumerator class which type to return.) Whereas the Cast function operates on IEnumerable, which will make it return a KeyValuePair.

您可以编写自己的角色的方法来解决这个问题,如果你真的的必须的使用非通用接口和的DictionaryEntry

You could write your own Cast method to work around this, if you really must use the non-generic interface and DictionaryEntry

IEnumerable<DictionaryEntry> CastDE(IDictionary dict) {
    foreach(var item in dict) yield return item;
}

这篇关于无法CAST()通用字典项的DictionaryEntry时,通过非一般的IDictionary枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆