Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在c中为foreach枚举哈希表#_C# - Fatal编程技术网

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

C# 如何在c中为foreach枚举哈希表#,c#,C#,我试图枚举一个哈希表,它的定义如下: private Hashtable keyPairs = new Hashtable(); foreach(SectionPair s in keyPairs) { if(s.Section == incomingSectionNameVariable) { bExists = true; break; } } // more stuff here 但我从Visual Studio 2013中得到一个错误,“

我试图枚举一个哈希表,它的定义如下:

private Hashtable keyPairs = new Hashtable();

foreach(SectionPair s in keyPairs)
{
   if(s.Section == incomingSectionNameVariable)
    {
      bExists = true;
      break;
    }
}
// more stuff here
但我从Visual Studio 2013中得到一个错误,“InvalidCastException未处理”。尽管使用字典,我还是想知道为什么会出现这个错误。

正如您在类的部分中所看到的,您列举的对象是。因此,您必须将其改写为:

foreach(DictionaryEntry s in keyPairs) {
   //Is Section the Key?
   if(s.Key == incomingSectionNameVariable) {
      bExists = true;
      break;
    }
}
字典入口
有一个
元素(当然是
哈希表
中的键和值)。这两个元素都是
对象
,因为
哈希表
不是泛型的,因此编译器无法知道
和/或
的类型

但是,我建议您使用,因为在这里您可以指定
值的类型。在这种情况下,示例如下所示:

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

foreach( KeyValuePair<string,int> kvp in keyPairs) {
    //do something with kvp
}
private Dictionary keyPairs=new Dictionary();
foreach(键对中的键值对kvp){
//用kvp做些什么
}

但是这里的
kvp.Key
将是一个
字符串,因此您不必强制转换它,而且使用起来更安全。

您确定
keyPairs
中的所有元素都可以强制转换为
SectionPair
?另外,您不应该使用非泛型
哈希表
。移动到泛型
哈希集
,以获得编译时类型安全性。Th这正是我需要理解的。愿风永远在你身后。-苏