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这正是我需要理解的。愿风永远在你身后。-苏