Deep Copy with Array

前端 未结 4 962
孤街浪徒
孤街浪徒 2021-01-19 19:06

Why doesn\'t ICloneable\'s Clone method return a deep copy?

Here is some sample code:

class A : ICloneable 
{
    public int          


        
相关标签:
4条回答
  • 2021-01-19 19:47

    Array.Copy copies the values of the array, in this case, references. There is nothing in the documentation of Array.Copy() that indicates a check for classes that implement IClonable and call Clone() instead. You will need to loop through the array and call Clone() yourself.

    BTW, yes, IClonable kind of sucks.

    0 讨论(0)
  • Array.Copy() does not use ICloneable. It simply copies values stored in each cell (which in this case are references to your A objects)

    0 讨论(0)
  • 2021-01-19 19:55

    Ani's answer uses LINQ thus does not work for C# 2.0, however a same method can be done using the Array class's ConvertAll method:

    A[] Array2 = Array.ConvertAll(Array1,a => (A)a.Clone());
    
    0 讨论(0)
  • 2021-01-19 20:02

    From http://msdn.microsoft.com/en-us/library/k4yx47a1.aspx:

    "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();
    
    0 讨论(0)
提交回复
热议问题