简体   繁体   English

添加到列表重新填充最后一个元素

[英]Adding to list repopulates with the last element

I'm creating a list of objects called MyComposedModel.我正在创建一个名为 MyComposedModel 的对象列表。

List<MyComposedModel> TheListOfModel = new List<MyComposedModel>();
MyComposedModel ThisObject = new MyComposedModel();

foreach (MyComposedModel in some list of MyComposedModel)
{
 ThisObject.Reset(); //clears all properties
 ....
 TheListOfModel.Add(ThisObject);
}

The problem is that each time the for-each loop iterates and executes the.Add statement, the list is repopulated with n+1 objects and every object in the list is ThisObject.问题在于,每次 for-each 循环迭代并执行 .Add 语句时,列表都会重新填充 n+1 个对象,并且列表中的每个 object 都是 ThisObject。 So for instance, the second time it runs, the last item is correctly inserted in position [1] BUT the first item in [0] is replaced with the second item and the list contains the second item in both positions.因此,例如,第二次运行时,最后一项正确插入 position [1] 但 [0] 中的第一项被第二项替换,并且列表在两个位置都包含第二项。

ThisObject has a property called ID and when I debug, I see the ID change so I know that it's going through the list but when it reaches the.Add line, I don't know what happens. ThisObject 有一个名为 ID 的属性,当我调试时,我看到 ID 发生了变化,所以我知道它正在遍历列表,但是当它到达 .Add 行时,我不知道会发生什么。

What am I missing?我错过了什么?

Thanks谢谢

You have only 1 object...您只有 1 个 object...

MyComposedModel is a reference type. MyComposedModel是一个引用类型。 You are filling a list with references to the same single object, and only the last properties stand.您正在填写一个引用同一个 object 的列表,并且只有最后一个属性存在。

What you probably need:你可能需要什么:

foreach (MyComposedModel otherObject in some list)
{
 //ThisObject.Reset();                  // clears all properties
   thisObject = new MyComposedModel();  // create a new instance instead
  ....
  TheListOfModel.Add(thisObject);
}

It looks like you're incorrectly re-using a reference to the same object over and over.看起来您一遍又一遍地错误地重复使用对相同 object 的引用。

When you do this:当你这样做时:

MyComposedModel ThisObject = new MyComposedModel();

That create a single reference to a new object and places it on the stack.这将创建对新 object 的单个引用并将其放置在堆栈上。 When you iterate your list and do this:当您迭代列表并执行此操作时:

ThisObject.Reset(); //clears all properties

It's still pointing to the SAME reference, you need to just create a new object of type "MyComposedModel", set it's properties and add it to the list.它仍然指向相同的引用,您只需创建一个类型为“MyComposedModel”的新 object,设置它的属性并将其添加到列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM