我在数组方面遇到了一点问题。 我是C#的新手。
我尝试使用以下方法将int
数组复制到另外两个int
数组中:
unsortedArray = randomNumbers();
unsortedArray2 = unsortedArray;
unsortedArray3 = unsortedArray;
但是,如果我对unsortedArray2
进行排序,那么unsortedArray3
也会被排序。
有人能帮帮我吗?
我试图将一个整数数组复制到另外两个整数数组中
重要的第一件事是在这行代码中:
unsortedArray2 = unsortedArray;
你没有将unsortedArray
的值复制到unsortedArray2
中。 =
被称为赋值运算符
赋值运算符(=)将其右操作数的值存储在存储位置中,
要理解此现象所需了解的第二件事是,C#中有两种类型的对象:引用类型和值类型
文档实际上已经很好地解释了:
引用类型的变量存储对其数据(对象)的引用,而值类型的变量直接包含其数据。使用引用类型,两个变量可以引用同一对象;因此,对一个变量的操作可能会影响另一个变量引用的对象。
解决方法可以使用Array.Copy方法。
Array.Copy(unsortedArray, 0, unsortedArray2 , 0, unsortedArray.Length);
在这种情况下,CopyTo 方法也可以使用。
unsortedArray.CopyTo(unsortedArray2 , 0);
注意:这将有效,因为数组的内容是值类型!如果它也是引用类型,更改其中一个项目的子值也会导致目标数组中同一项目的更改。
unsortedArray2
和unsortedArray3
指向同一块内存,当您重新排序数组时,只是操作了这个内存块。
有了这个理解,我们需要实现什么来达到您的目标?我们需要复制数组。可以用许多方法来完成:
Array.Copy(unsortedArray, 0, unsortedArray2 , 0, unsortedArray.Length);
// The CopyTo method would also work in this case
unsortedArray.CopyTo(unsortedArray2 , 0);
var unsortedArray2 = new int[unsortedArray.Length];
for (int i = 0; i < unsortedArray.Length; i++)
{
unsortedArray2[i] = unsortedArray[i];
}
var unsortedArray2 = unsortedArray.Clone();
unsortedArray = randomNumbers();
Array.Copy(unsortedArray, unsortedArray2 , unsortedArray.Length);
Array.Copy(unsortedArray, unsortedArray3 , unsortedArray.Length);
这对我来说可行,我认为这更容易。
int[] unsortedArray = randomNumbers();
int[] unsortedArray2 = unsortedArray.ToArray();
int[] unsortedArray3 = unsortedArray.ToArray();
虽然这可能不能回答你的标题问题,但你可以使用List
:
List<int> unsortedArray2 = unsortedArray.ToList();
int[] unsortedArray2 = new int[unsortedArray.Length];
unsortedArray.CopyTo(unsortedArray2, 0);
unsortedArray = randomNumbers();
unsortedArray2 = unsortedArray.Clone;
unsortedArray.CopyTo(unsortedArray2, 0);
unsortedArray3 = unsortedArray.Clone;
unsortedArray.CopyTo(unsortedArray3, 0);
Array.Sort(unsortedArray2);
int[] source = {1, 2, 3, 4, 5}; int[] target = new int[5]; Array.Copy(source, target, 5); // 输出: target数组中的元素为1 2 3 4 5 for (int i = 0; i < target.Length; i++) { Console.Write(target[i] + " "); }
- tym32167