将数组复制到数组 [英] Copy Arrays to Array

查看:49
本文介绍了将数组复制到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对数组有点问题.我是 C# 新手.

I have a little Problem with Arrays. I am new in C#.

我尝试将一个 Int Array 复制到另外 2 个 Int Arrays 中

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 Array 复制到另外 2 个 Int Arrays 中

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,

现在要理解这种现象,您需要知道的第二件事是 C# 中有两种类型的对象 引用类型和值类型

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆