C# 将一个二维数组复制到另一个二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15725840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy one 2D array to another 2D array
提问by user2079550
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?
但是,当我更改某些数据时,tempPerformance
这些更改也适用于teamPerformance
.
我该怎么做才能控制它?
采纳答案by dasblinkenlight
This is correct: Array.Copy
performs a shallowcopy, so the instances of arrays inside the inner dimension get copied by reference. You can use LINQ to make a copy, like this:
这是正确的:Array.Copy
执行浅复制,因此内部维度内的数组实例通过引用进行复制。您可以使用 LINQ 进行复制,如下所示:
var copy2d = orig2d.Select(a => a.ToArray()).ToArray();
Here is a demo on ideone.
回答by Sheng
According to MS(http://msdn.microsoft.com/en-us/library/z50k9bft.aspx):
根据 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.
如果sourceArray 和destinationArray 都是引用类型数组或者都是Object 类型的数组,则执行浅拷贝。Array 的浅拷贝是一个新的 Array,其中包含对与原始 Array 相同元素的引用。元素本身或元素引用的任何内容都不会被复制。相比之下,数组的深层副本复制元素以及元素直接或间接引用的所有内容。
回答by Sergey Kulgan
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