按顺序进行Hashtable遍历

Dav*_*vid 1 c# hashtable visual-studio-2008

我在我的类中写了一个简短的静态方法Hashtable,按顺序迭代我的一些s,string但是我得到了一个奇怪的编译器错误.这是有问题的方法:

public static DictionaryEntry inorderHashtable(Hashtable ht) {
    string[] keys = ht.Keys.Cast<string>().ToArray<string>();
    Array.Sort(keys);

    foreach (string key in keys) {
        yield return new DictionaryEntry(key, ht[key]);
    }
}
Run Code Online (Sandbox Code Playgroud)

这稍后在类中使用,如下所示:

foreach(DictionaryEntry dentry in inorderHashtable(myTable)) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

这是我从VS2008得到的错误: 'ns.myclass.inorderHashtable(System.Collections.Hashtable)' cannot be an iterator block because 'System.Collections.DictionaryEntry' is not an iterator interface type

有什么方法可以解决这个错误?提前致谢.

Raw*_*ing 5

您的方法需要具有返回类型IEnumerable<DictionaryEntry>.

基本上,通过使用yield return而不是return,你没有返回一个 DictionaryEntry,你(可能)返回许多.

如果你不确定发生了什么,请看这里这里.