开发者

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

开发者 https://www.devze.com 2023-04-11 14:23 出处:网络
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 thoug

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"}};
fore开发者_如何学编程ach (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?


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(DictionaryEntry item in dict)
        yield return item;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号