C# - List member needs deep copy?

后端 未结 3 1947
独厮守ぢ
独厮守ぢ 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:16

    If you have List originalList = new List{1, 2} then doing this:
    List newList = new List();
    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.

提交回复
热议问题