我有我Newtonssoft Json.Net反序列化這樣一個JSON文件:反序列化的JSONObject得到更新,然後的foreach失敗
/* Get current config */
dynamic json = JsonConvert.DeserializeObject<Speaker>(
File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "cfg\\speaker.json"));
dynamic jsonDevice = json.DeviceList;
/* Go through the List */
foreach (Tapi tapi in lvTapiSonos.Items)
{
foreach (var line in jsonDevice)
{
foreach (var l in line)
{
/* If not in List already, add it */
if (l.Key != tapi.Name)
{
/* Add to Config */
json.DeviceList.Add(new Dictionary<string, List<Device>>
{
{
tapi.Name,
new List<Device>
{
new Device
{
Volume = "5",
Ip = currentEditIp,
Name = currentEditName
}
}
}
});
}
}
}
}
string output = JsonConvert.SerializeObject(json, Formatting.Indented);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "cfg\\speaker.json", output);
不幸的只適用於第一foreach
,因爲我得到一個例外「列表已經改變了,枚舉不能繼續,「(與我在德語中的類似)在foreach (var line in jsonDevice)
行中。
我明白這意味着,jsonDevice
已經更新(它現在顯示在調試一個多項目),但因爲我分配jsonDevice
外的foreach,它是如何更新?當我更新foreach中的json Object時,產生了foreach var line in json.DeviceList
產生錯誤似乎是合乎邏輯的,但爲什麼這仍然會發生?
知道的任何線索......
我想這是通過引用創建,: 動態jsonDevice = JSON。DEVICELIST; –
它確實是一個參考複製到相同的分配,從而導致在'foreach'循環修改中的問題 –