Unable to Cast() generic dictionary item to DictionaryEntry when enumerated via non-generic IDictionary

≯℡__Kan透↙ 提交于 2019-12-12 12:24:55

问题


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

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?


回答1:


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.

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;
}


来源:https://stackoverflow.com/questions/7683294/unable-to-cast-generic-dictionary-item-to-dictionaryentry-when-enumerated-via

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