我正在尝试枚举定义为的哈希表:
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
有一个 Key
和 Value
元素(它们当然是 Hashtable
中的键和值。两者都是 Object
s,因为 Hashtable
不是通用的,因此编译器无法知道 Key
和//67915 的类型或 Value
是。
不过,我建议您使用 Dictionary<TKey,TValue>
,因为您可以在此处指定 Key
和 Value
的类型。在这种情况下,示例可能如下所示:
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/