Cannot include () a generic dictionary element in DictionaryEntry when enumerating through a non-generic IDictionary

I have some code that IDictionary over a non-generic IDictionary by first calling LINQ Cast . However, I get an invalid cast exception when passing a generic dictionary implementation, even if I specifically use it through a non-generic IDictionary .

 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 doesn't the Cast method work when normal iteration doesn't work? Is there a reliable way to convert a non-generic dictionary to a DictionaryEntry enumeration without resorting to creating a manual list?

+4
source share
1 answer

The problem is that the IEnumerable implementation on Dictionary<TKey,TValue> lists KeyValuePairs. Foreach on an IDictionary will use the IDictionary.GetEnumerator function, which returns an IDictionaryEnumerator (internally this tells the IEnumerator function for the inner class Enumerator whose type is returned). While the Cast function works on IEnumerable, which will make it return KeyValuePair.

You can write your own Cast method to get around this if you really have to use a non-common interface and DictionaryEntry

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

Source: https://habr.com/ru/post/913511/


All Articles