for 循环未按预期工作 C#
本文关键字:工作 循环 for | 更新日期: 2023-09-27 18:36:02
我正在研究这个for
循环,但我遇到了一个严重困扰我的问题。当执行for
循环时,它应该返回
{"MonID":"1","MonMapID":0}
{"MonID":"1","MonMapID":1}
{"MonID":"1","MonMapID":2}
{"MonID":"1","MonMapID":3}
但它没有返回,它正在返回
{"MonID":"1","MonMapID":3}
{"MonID":"1","MonMapID":1}
{"MonID":"1","MonMapID":2}
{"MonID":"1","MonMapID":3}
这是我运行的代码
JObject mapMonBranch = new JObject();
JArray monList = new JArray();
string[] monB = room.Mon.Split(Convert.ToChar(","));
for (int index = 0; index < monB.Length; index++)
{
var monData = monB[index];
if (string.IsNullOrEmpty(monData)) continue;
mapMonBranch ["MonID"] = monData;
mapMonBranch ["MonMapID"] = index;
monList.Add(mapMonBranch);
}
代码有什么问题?我非常困惑。
您要向列表中添加对同一对象的四个引用。添加到列表中会添加对该对象的引用,它不会创建该对象的新副本,因此如果您修改该对象,列表中的所有条目都将更改。每次要添加一个对象时,都需要创建一个对象的新实例,例如:
JArray monList = new JArray();
string[] monB = room.Mon.Split(Convert.ToChar(","));
for (int index = 0; index < monB.Length; index++)
{
var monData = monB[index];
if (string.IsNullOrEmpty(monData)) continue;
JObject mapMonBranch = new JObject();
mapMonBranch["MonID"] = monData;
mapMonBranch["MonMapID"] = index;
monList.Add(mapMonBranch);
}
你应该在循环中创建mapmon对象的新实例,如下所示:
JObject mapMonBranch = new JObject();
JArray monList = new JArray();
JObject mapMon = new JObject();
string[] monB = room.Mon.Split(Convert.ToChar(","));
for (int index = 0; index < monB.Length; index++)
{
var monData = monB[index];
if (string.IsNullOrEmpty(monData)) continue;
mapmon = new JObject();
mapMon["MonID"] = monData;
mapMon["MonMapID"] = index;
monList.Add(mapMonBranch);
}