How do I change my new list without changing the original list?

后端 未结 11 1882
萌比男神i
萌比男神i 2020-12-03 08:30

I have a list that gets filled in with some data from an operation and I am storing it in the memory cache. Now I want another list which contains some sub data from the li

11条回答
  •  鱼传尺愫
    2020-12-03 09:04

    You'll need to make a copy of the list since in your original code what you're doing is just passing around, as you correctly suspected, a reference (someone would call it a pointer).

    You could either call the constructor on the new list, passing the original list as parameter:

    List SomeOperationFunction(List target)
    {
        List result = new List(target);
        result.removeat(3);
        return result;
    }
    

    Or create a MemberWiseClone:

    List SomeOperationFunction(List target)
    {
        List result = target.MemberWiseClone();
        result.removeat(3);
        return result;
    }
    

    Also, you are not storing the return of SomeOperationFunction anywhere, so you might want to revise that part as well (you declared the method as void, which should not return anything, but inside it you're returning an object). You should call the method this way:

    List target = SomeOperationFunction(mainList);
    

    Note: the elements of the list will not be copied (only their reference is copied), so modifying the internal state of the elements will affect both lists.

提交回复
热议问题