作者petrushka (不放过自己)
看板C_Sharp
标题Re: [问题] 物件阵列的复制
时间Mon May 31 10:55:32 2010
原PO的问题出在value type与reference type上。
Array本身是reference type,自定类别也是reference type。
查阅MSDN Array.Copy的说明,你会发现其中有一段说明如下:
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. In contrast, a deep copy of an Array copies the
elements and everything directly or indirectly referenced by the elements.
同理,如
Clone method,你可以参照下面这个连结,里面有张示意图(图有点小):
http://en.csharp-online.net/All_about_Arrays_in_CSharp%E2%80%94Clone_Method
结果差异是:
1. Cloning a value type array results in two independent arrays.
2. Cloning a reference type array results in two arrays pointing at the same
objects.
因此,reference type array是elements的集合,而每一个element指向一个object,这
样的情况就带来了影响。
在.NET,几乎提供的都是shallow copy,如果要达成自己所需要的deep copy,就只有
自己实作一途了。
同常为了要实作这个,类别会去继承
ICloneable。
或是你可以透过Serialize和Deserialize来达到同样目的(但这个成本不小)。
但是我觉得真正应该要思考的是
"真的需要Deep Copy吗?"
就经验,如能调整程式架构或过程做法,似乎不需要这样的功能。甚至连shallow copy
都几乎用不到。
--
对於已经无法拥有的
唯一能做的是
不要忘记
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.125.251.180
※ 编辑: petrushka 来自: 140.125.251.180 (05/31 10:59)