c# - 如何在 C# 中为 foreach 枚举哈希表

标签 c#

我正在尝试枚举定义为的哈希表:

private Hashtable keyPairs = new Hashtable();

foreach(SectionPair s in keyPairs)
{
   if(s.Section == incomingSectionNameVariable)
    {
      bExists = true;
      break;
    }
}
// more stuff here

但我从 Visual Studio 2013 收到错误消息“InvalidCastException 未处理”。尽管使用字典,但我很想知道为什么会出现此错误。

最佳答案

正如您在 Remarks 类的 Hashtable 部分中所读到的,您枚举的对象是 DictionaryEntry s 。因此,您必须将其重写为:

foreach(DictionaryEntry s in keyPairs) {
   //Is Section the Key?
   if(s.Key == incomingSectionNameVariable) {
      bExists = true;
      break;
    }
}

A DictionaryEntry 有一个 KeyValue 元素(它们当然是 Hashtable 中的键和值。两者都是 Object s,因为 Hashtable 不是通用的,因此编译器无法知道 Key 和//67915 的类型或 Value 是。

不过,我建议您使用 Dictionary<TKey,TValue> ,因为您可以在此处指定 KeyValue 的类型。在这种情况下,示例可能如下所示:

private Dictionary<string,int> keyPairs = new Dictionary<string,int>();

foreach( KeyValuePair<string,int> kvp in keyPairs) {
    //do something with kvp
}

但这里的 kvp.Key 将是 string,因此您不必转换它并且使用起来更安全。

关于c# - 如何在 C# 中为 foreach 枚举哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41495278/

相关文章:

c# - 在字符串中间插值

c# - 使用 JSON 在 C# 中调用 API

c# - .NET XmlSerializer(反)使用架构编译器 xsd.exe 和错误的命名空间绑定(bind)从不同的命名空间序列化派生类型

c# - 使用 DialogResult.Cancel 的优势

c# - .Net 页面响应缺少响应正文的一部分

c# - 动态方法预链接

c# - 如何让 J# 与 VS 2010 和 .NET 4 一起工作

c# - 如何查询所有子文件夹?

c# - 当 Enum 在 ViewModel 中时将 Enum 值作为 CommandParameter 传递

c# - 来自内部文件夹的 ASP.NET Server.Mappath 问题