22

I used this code to copy one 2D array to another 2D array:

Array.Copy(teamPerformance, 0,tempPerformance,0, teamPerformance.Length);

However, when I change some data in tempPerformance then these changes also apply to teamPerformance.
What should I do to control that?

4

3 回答 3

60

You need Clone()

double[,] arr = 
{
   {1, 2},
   {3, 4}
};
double[,] copy = arr.Clone() as double[,];
copy[0, 0] = 2;
//it really copies the values, not a shallow copy, 
//after:
//arr[0,0] will be 1
//copy[0,0] will be 2
于 2016-09-01T22:38:22.053 回答
17

This is correct: Array.Copy performs a shallow copy, so the instances of arrays inside the inner dimension get copied by reference. You can use LINQ to make a copy, like this:

var copy2d = orig2d.Select(a => a.ToArray()).ToArray();

Here is a demo on ideone.

于 2013-03-31T02:52:19.803 回答
3

According to MS(http://msdn.microsoft.com/en-us/library/z50k9bft.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. In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.

于 2013-03-31T02:54:35.767 回答