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

后端 未结 11 1865
萌比男神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

    Since a List is a reference type, what is passed to the function is a reference to the original list.

    See this MSDN article for more information about how parameters are passed in C#.

    In order to achieve what you want, you should create a copy of the list in SomeOperationFunction and return this instead. A simple example:

    void List SomeOperationFunction(List target)
    {
      var newList = new List(target);
      newList.RemoveAt(3);
      return newList; // return copy of list
    }
    

    As pointed out by Olivier Jacot-Descombes in the comments to another answer, it is important to bear in mind that

    [...] the list still holds references to the same items if the items are of a reference type. So changes to the items themselves will still affect the items in both lists.

提交回复
热议问题