C# - List member needs deep copy?

后端 未结 3 1854
独厮守ぢ
独厮守ぢ 2021-01-12 19:51

I have class with a List member. If I want to clone an instance of this class, do I need a deep copy or the MemberwiseClone() shallow co

相关标签:
3条回答
  • 2021-01-12 20:08

    Short answer, yes.

    Long answer, you need to determine what the copy in your case actually means with respect to the list. Do you need a copy of the contents of the list as well? For value types like ints, its pretty straight forward, if it were reference types though....yo have some questions to ask regarding what you want your list to contain.

    0 讨论(0)
  • 2021-01-12 20:15

    This entirely depends on how you plan to use the copy.

    If you do a shallow copy like

    List<int> x = new List<int>() { 1, 2, 3, 4, 5 };
    List<int> y = x;
    y[2] = 4;
    

    Then x will contain {1, 2, 4, 4, 5 }

    If you do a deep copy of the list:

    List<int> x = new List<int> { 1, 2, 3, 4, 5 };
    List<int> y = new List<int>(x);
    y[2] = 4;
    

    Then x will contain { 1, 2, 3, 4, 5 } and y will contain { 1, 2, 4, 4, 5 }

    How you plan on using the copy really determines whether you use shallow or deep copies.

    0 讨论(0)
  • 2021-01-12 20:16

    If you have List<int> originalList = new List{1, 2} then doing this:
    List<int> newList = new List<int>();
    foreach(int i in originalList)
    newList.Add(i);

    will get you a cloned list.

    However, if you tried what I did above with a List generic on some reference type, then you would not succeed. After altering one of the objects in your list, you would see the altered version whether referencing it from the original list or the new list.

    0 讨论(0)
提交回复
热议问题