我在我的类中写了一个简短的静态方法来迭代一些 Hashtable
s 我按照键(string
s)的顺序但是我得到了一个奇怪的编译器错误。这是有问题的方法:
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]);
}
}
稍后在类中这样使用:
foreach(DictionaryEntry dentry in inorderHashtable(myTable)) { /* ... */ }
这是我从 VS2008 得到的错误:'ns.myclass.inorderHashtable(System.Collections.Hashtable)' cannot be an iterator block because 'System.Collections.DictionaryEntry' is not an iterator interface type
如何解决这个错误?提前致谢。
最佳答案
您的方法需要具有返回类型 IEnumerable<DictionaryEntry>
.
基本上,通过使用 yield return
而不是 return
,你不会返回一个 DictionaryEntry
,您(可能)返回许多。
关于c# - 有序Hashtable遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12058564/