Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c# - Deep Copy with Array

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

Here is some sample code:

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;
     }
}

In the Main method :

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}");

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

Index 2 in Array1 has 11 even though I changed it in Array2 and class A implements ICloneable!

What then is the benefit of Array implementing ICloneable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...