将阵列复制到阵列 [英] Copy Arrays to Array
问题描述
我对数组有一点问题.我是C#新手.
I have a little Problem with Arrays. I am new in C#.
我尝试使用以下方式将一个Int数组复制到其他2个Int数组中:
I try to copy a Int Array into 2 other Int Arrays with
unsortedArray = randomNumbers();
unsortedArray2 = unsortedArray;
unsortedArray3 = unsortedArray;
但是,如果我对unsortedArray2进行排序,那么unsortedArray3也将进行排序.
but, if i sort the unsortedArray2, the unsortedArray3 is sorted too.
有人可以帮我吗?
推荐答案
我尝试使用以下方式将一个Int数组复制到其他2个Int数组中:
I try to copy a Int Array into 2 other Int Arrays with
重要的第一件事是在这一行:
The first thing that is important is that in this line :
unsortedArray2 = unsortedArray;
您不会将unsortedArray
的值复制到unsortedArray2
中. =
称为分配运算符
you do not copy the values of the unsortedArray
into unsortedArray2
. The =
is called the assignment operator
赋值运算符(=)将其右侧操作数的值存储在存储位置,
The assignment operator (=) stores the value of its right-hand operand in the storage location,
Now the second thing that you need to know to understand this phenomenon is that there are 2 types of objects in C# Reference Types and Value types
文档实际上对它进行了很好的解释:
The documentation explains it actually quite nicely:
引用类型的变量存储对其数据(对象)的引用,而值类型的变量直接包含其数据.对于引用类型,两个变量可以引用相同的对象.因此,对一个变量的操作可能会影响另一变量引用的对象.
Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.
解决方案可以是使用阵列.复制方法.
The solution can be to use the Array.Copy method.
Array.Copy(unsortedArray, 0, unsortedArray2 , 0, unsortedArray.Length);
CopyTo 方法也将在这种情况下工作
The CopyTo method would also work in this case
unsortedArray.CopyTo(unsortedArray2 , 0);
注意:这将起作用,因为数组的内容是值类型!如果它也是引用类型,则更改其中一项的子值也将导致目标数组中同一项的更改.
Note:this will work because the content of the array is a value type! If it would be also of reference type, changing a sub value of one of the items would lead also to a change in the same item in the destination array.
这篇关于将阵列复制到阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!