Adding to list repopulates with the last element

前端 未结 2 1380
暗喜
暗喜 2021-01-25 16:54

I\'m creating a list of objects called MyComposedModel.

List TheListOfModel = new List();
MyComposedModel ThisObjec         


        
相关标签:
2条回答
  • 2021-01-25 17:10

    It looks like you're incorrectly re-using a reference to the same object over and over.

    When you do this:

    MyComposedModel ThisObject = new MyComposedModel();
    

    That create a single reference to a new object and places it on the stack. 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.

    0 讨论(0)
  • 2021-01-25 17:23

    You have only 1 object...

    MyComposedModel is a reference type. You are filling a list with references to the same single object, and only the last properties stand.

    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);
    }
    
    0 讨论(0)
提交回复
热议问题