0

新添加到列表中的数据将替换 a 中的先前值list<>。在以下代码中, listRM包含Address信息中的所有项目。我究竟做错了什么?

 public void Assign(Rprts PrevItem, Rprts CurrentItem, List<Fields> listRM)
        {
            Fields field = new Fields();
            field.hding = "Name :";
            field.FName = PrevItem.fname;
            field.LName = PrevItem.lname;
            field.addrs1 = "";
            field.addrs2 = "";
            field.City = "";


            listRM.Add(field);


            field.hding = "Address :";
            field.Qty = "";
            field.Name = "";
            field.Dept = "";
            field.addrs1 = "ABC";
            field.addrs2 = "XYZ";
            field.City = "UVW";
            listRM.Add(field);

        }
4

2 回答 2

1

Field您必须为要添加的每个条目创建一个新实例。

第一次调用时listRM.Add(field),您传递了对对象的引用field(这也只是一个引用)。当您更改此对象时,列表指向的对象也会更改。

您可以通过在第二次调用之前放置一个断点来查看这一点,listRM.Add(field)并检查field' 和listRM.Results' 的值,例如但不一定使用QuickWatch

现在开始创建一个新项目,只需执行以下操作:

field = new Field();
field. // set properties again
listRM.Add(field);
于 2013-03-14T00:04:23.347 回答
1

You've created ONE instance of Fields class and added the same object to the list twice modifying that object in the middle. So your list, as expected, would contain that object twice, but both list items will point to the same modified instance field. Try creating brand new objects for every item you intend to add to the list: Fields field = new Fields();

于 2013-03-14T00:07:51.070 回答