问题
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