原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)