我有一本字典如下:
IDictionary<string, string> dict;
如何创建一个实现IDictionaryEnumerator的枚举器(最好使用linq)?
答案 0 :(得分:3)
在这里一定要遗漏一些东西,如下:
IDictionary obsoleteDict = dict as IDictionary;
if (obsoleteDict == null)
{
//Do something here...
}
else
{
return obsoleteDict.GetEnumerator();
}
(编辑:是的,你必须将它转换为旧的非通用接口)
edit2:请参阅下面的Pavel评论。实现IDictionary<K,V>
的类型可能会也可能不会实现IDictionary(Dictionary<K,V>
会执行,而某些实现(如WCF的MessageProperties)则不会),因此强制转换可能不起作用。
答案 1 :(得分:3)
IDictionaryEnumerator
实际上是仿制前版本;你应该只能使用IEnumerator<KeyValuePair<string,string>>
...
当然,你可以封装;这将适用于自定义实现:
using System;
using System.Collections;
using System.Collections.Generic;
static class Program
{
class MyEnumerator<TKey,TValue> : IDictionaryEnumerator, IDisposable
{
readonly IEnumerator<KeyValuePair<TKey, TValue>> impl;
public void Dispose() { impl.Dispose(); }
public MyEnumerator(IDictionary<TKey, TValue> value)
{
this.impl = value.GetEnumerator();
}
public void Reset() { impl.Reset(); }
public bool MoveNext() { return impl.MoveNext(); }
public DictionaryEntry Entry { get { var pair = impl.Current;
return new DictionaryEntry(pair.Key, pair.Value);} }
public object Key { get { return impl.Current.Key; } }
public object Value { get { return impl.Current.Value; } }
public object Current {get {return Entry;}}
}
static IDictionaryEnumerator GetBasicEnumerator<TKey,TValue>(
this IDictionary<TKey, TValue> data)
{
return new MyEnumerator<TKey, TValue>(data);
}
static void Main()
{
IDictionary<int, string> data = new Dictionary<int, string>()
{
{1,"abc"}, {2,"def"}
};
IDictionaryEnumerator basic;
using ((basic = data.GetBasicEnumerator()) as IDisposable)
{
while (basic.MoveNext())
{
Console.WriteLine(basic.Key + "=" + basic.Value);
}
}
}
}
答案 2 :(得分:2)
我认为IDictionaryEnumerator
仅由非泛型字典类型实现。通用字典类公开IEnumerator
。
由于泛型字典返回强类型的KeyValuePair项,因此IDictionaryEnumerator的功能似乎是多余的。如果可能,您应该尝试调整代码,只使用IEnumerator<KeyValuePair<K,V>>
。
答案 3 :(得分:1)
在大多数情况下,这将有效。然后它不会引发异常。
return (IDictionaryEnumerator)dict.GetEnumerator();
至少以下BCL类型返回实现IDictionaryEnumerator的枚举器(这些是我检查过的):
Hashtable
(强制执行公共API)Dictionary<T,K>
(强制执行公共API)SortedList<T,K>
(不受公共API保证,但实现确实实现了它)