简体   繁体   中英

Deep copy of an object into List

I have a loop:

List<A> list = new List<A>();
A obj = new A();

for (int i = 0; i < 10; ++i)
{
    obj.num = i; // Assigns the current i to the num attribute inside obj
    list.Add(obj);
}

However, in this case, whenever I modify obj , the previous instances of obj already added into the list will be modified. How do I write the code such that whatever that is added into the list has no more reference to the current value of obj ?

You can create a new List<A> via Linq instead of adding:

List<A> list = Enumerable
  .Range(0, 10)
  .Select(i => new A() { num = i })
  .ToList();

If you prefer adding

List<A> list = new List<A>();

for (int i = 0; i < 10; ++i)
  list.Add(new A() {num = i}); // <- Adding new (copied) instance 

you should move declaration of obj variable inside for loop

List<A> list = new List<A>();

for (int i = 0; i < 10; ++i)
{
    A obj = new A();
    obj.num = i; // Assigns the current i to the num attribute inside obj
    list.Add(obj);
}

it is all just about variable scopes. here obj scope is inside a for loop iteration. if you want to use a variable between iterations you should define it out of for loop like the way you have declared obj before.

That's happening because probably A obj = new A(); is a ByReference object. So whenever you're in the loop, it's also changing the object you added on the List.

What you can do is either

  1. Create the object inside the loop and then add it.

     for (int i = 0; i < 10; ++i) { A obj = new A(); // create here so it's a new object always obj.num = i; // Assigns the current i to the num attribute inside obj list.Add(obj); } 
  2. Make the A type IClonable

     class A : ICloneable { public object Clone() { return this.MemberwiseClone(); } } 

and then just cast in before adding.

List<A> list = new List<A>();
A obj = new A();
obj.num = 0;

for (int i = obj.num; i < 10; ++i)
{
    var clonedObj = obj.Clone() as A; // cast to be able to add in the collection
    clonedObj.num = i;
    list.Add(clonedObj);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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