数组深度复制 [英] Deep Copy with Array
问题描述
为什么 ICloneable
的 Clone
方法不返回深拷贝?
Why doesn't ICloneable
's Clone
method return a deep copy?
这是一些示例代码:
class A : ICloneable
{
public int x = 2;
public A(int x)
{
this.x = x;
}
public A copy()
{
A a = new A(this.x);
return a;
}
public object Clone()
{
A a = new A(this.x);
return a;
}
}
在Main
方法中:
A[] Array1 = new A[4] ;
Array1[0] = new A(0);
Array1[1] = new A(1);
Array1[2] = new A(2);
Array1[3] = new A(3);
A[] Array2 = new A[10];
Array. Copy(Array1, Array2, 4);
Array2[2].x = 11;
for (int i = 0; i < 4; i++)
Console.WriteLine($"Index {i} value: {Array1[i].x}");
记住我只改变了 Array2
中的元素索引 2,这是上面代码的输出,列出了 Array1
中的值:
Remembering that I've only changed element index 2 in Array2
, here is the output from the code above, listing the values in Array1
:
Index 0 value: 0
Index 1 value: 1
Index 2 value: 11
Index 3 value: 3
Array1
中的索引 2 具有 11
即使我在 Array2
中更改了它并且 class A
实现了 ICloneable
!
Index 2 in Array1
has 11
even though I changed it in Array2
and class A
implements ICloneable
!
Array
实现 ICloneable
有什么好处?
What then is the benefit of Array
implementing ICloneable
?
推荐答案
来自 http://msdn.microsoft.com/en-us/library/k4yx47a1.aspx:
"如果sourceArray 和destinationArray 都是引用类型的数组或者都是Object 类型的数组,则执行浅拷贝.Array 的浅拷贝是一个新的Array,其中包含对与原始Array 相同元素的引用.元素本身或元素引用的任何内容都不会被复制"
"If sourceArray and destinationArray are both reference-type arrays or are both arrays of type Object, a shallow copy is performed. A shallow copy of an Array is a new Array containing references to the same elements as the original Array. The elements themselves or anything referenced by the elements are not copied"
可能有比这更好的方法,但您可以使用的一种技术是:
There may be a better method than this, but one technique you could use is:
A[] array2 = array1.Select (a =>(A)a.Clone()).ToArray();
这篇关于数组深度复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!