我正在尝试更新循环中的哈希表,但收到错误:System.InvalidOperationException:Collection已被修改; 枚举操作可能无法执行.
private Hashtable htSettings_m = new Hashtable(); htSettings_m.Add("SizeWidth", "728"); htSettings_m.Add("SizeHeight", "450"); string sKey = ""; string sValue = ""; foreach (DictionaryEntry deEntry in htSettings_m) { // Get value from Registry and assign to sValue. // ... // Change value in hashtable. sKey = deEntry.Key.ToString(); htSettings_m[sKey] = sValue; }
有没有方法或者为此目的有更好的数据结构?
你可以先将密钥集合读入另一个IEnumerable实例,然后再遍历该列表
System.Collections.Hashtable ht = new System.Collections.Hashtable(); ht.Add("test1", "test2"); ht.Add("test3", "test4"); Listkeys = new List (); foreach (System.Collections.DictionaryEntry de in ht) keys.Add(de.Key.ToString()); foreach(string key in keys) { ht[key] = DateTime.Now; Console.WriteLine(ht[key]); }