【问题标题】:In order Hashtable traversal为了Hashtable遍历
【发布时间】:2012-08-21 15:46:53
【问题描述】:

我在我的类中编写了一个简短的静态方法来迭代一些 Hashtables 我按键的顺序 (strings) 但我遇到了一个奇怪的编译器错误。这是有问题的方法:

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

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

【问题讨论】:

  • 值得一提的是,您可以只 return ht.Keys.Cast&lt;string&gt;().OrderBy(key =&gt; key).Select(key =&gt; ...); 并相应地更改返回类型。
  • HashTable 在这一点上也已过时。如果可能的话,你真的应该使用Dictionary

标签: c# visual-studio-2008 hashtable


【解决方案1】:

你的方法需要有返回类型IEnumerable&lt;DictionaryEntry&gt;

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

如果您不确定发生了什么,请参阅 herehere

【讨论】:

  • 我收到错误消息“非泛型类型 'System.Collections.IEnumerable' 不能与类型参数一起使用”,但仅返回 IEnumerable 即可正常工作。感谢您的帮助。
  • @David 你真的应该修复代码以使用通用的IEnumerable 接口。我的猜测是你只需要为通用命名空间添加一个 using 就可以了。
  • @Servy,这确实是using 的问题。再次感谢。
猜你喜欢
  • 2016-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多