我试图列举一个Hashtable
其定义为:
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 https://msdn.microsoft.com/en-us/library/system.collections.hashtable(v=vs.110).aspx#Anchor_7的部分Hashtable https://msdn.microsoft.com/en-us/library/system.collections.hashtable类,您枚举的对象是DictionaryEntrys https://msdn.microsoft.com/en-us/library/system.collections.dictionaryentry(v=vs.110).aspx。所以你必须将其重写为:
foreach(DictionaryEntry s in keyPairs) {
//Is Section the Key?
if(s.Key == incomingSectionNameVariable) {
bExists = true;
break;
}
}
A DictionaryEntry
has a Key
and Value
元素(当然是元素中的键和值)Hashtable
。两者都是Object
自从aHashtable
不是通用的,因此编译器无法知道该类型是什么Key
and/or Value
is.
不过我建议你使用Dictionary<TKey,TValue> https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx因为在这里您可以指定的类型Key
and Value
。在这种情况下,示例可能如下所示:
private Dictionary<string,int> keyPairs = new Dictionary<string,int>();
foreach( KeyValuePair<string,int> kvp in keyPairs) {
//do something with kvp
}
但在这儿kvp.Key
将是一个string
所以你不必铸造它,使用起来更安全。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)