C# - 列表成员需要深拷贝? [英] C# - List member needs deep copy?
问题描述
我有一个列表与LT类; INT>
成员。如果我想克隆这个类的一个实例,我需要深拷贝或 MemberwiseClone()
浅复制是不够吗?
I have class with a List<int>
member. If I want to clone an instance of this class, do I need a deep copy or the MemberwiseClone()
shallow copy is enough?
我们需要的,如果至少有一个成员是一个对象的引用,对深拷贝?这是否意味着有列表,日期时间,字符串,MyClass的,......,将需要深拷贝?
We need a deep copy if at least one member is a reference to an object, right? Does that mean having List, DateTime, String, MyClass, ..., will need a deep copy?
推荐答案
这完全取决于你打算如何使用该副本。
This entirely depends on how you plan to use the copy.
如果你做一个浅拷贝像
List<int> x = new List<int>() { 1, 2, 3, 4, 5 };
List<int> y = x;
y[2] = 4;
那么x将包含{1,2,4,4,5}
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;
那么x将包含{1,2,3,4,5}和y将包含{1 ,2,4,4,5}
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.
这篇关于C# - 列表成员需要深拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!