Adding to list repopulates with the last element

前端 未结 2 1384
暗喜
暗喜 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: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);
    }
    

提交回复
热议问题