for循环不能按预期工作C#

时间:2016-02-23 16:40:29

标签: c#

我正在研究这个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);
}

代码有什么问题?我很困惑。

2 个答案:

答案 0 :(得分:1)

您要将同一对象的四个引用添加到列表中。添加到列表会添加对该对象的引用,它不会创建该对象的新副本,因此如果您修改该对象,列表中的所有条目都将更改。每次要添加对象时,都需要创建对象的新实例:

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);
}

答案 1 :(得分:0)

您应该在循环中创建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);
}