简体   繁体   English

C# - 使用CopyTo()-Help进行数组复制

[英]C# - Array Copying using CopyTo( )-Help

I have to copy the following int array in to Array : 我必须将以下int数组复制到Array中:

int[] intArray=new int[] {10,34,67,11};

i tried as 我试过了

Array copyArray=Array.CreateInstance(typeof(int),intArray.Length,intArray);
intArray.CopyTo(copyArray,0);

But ,it seems i have made a mistake,so i did not get the result. 但是,似乎我犯了一个错误,所以我没有得到结果。

Are you aware that an int[] is already an Array ? 你知道int[]已经是一个Array吗? If you just need to pass it to something accepting Array , and you don't mind if it changes the contents, just pass in the original reference. 如果你只需要将它传递给接受Array东西,并且你不介意它是否改变了内容,只需传入原始引用即可。

Another alternative is to clone it: 另一种方法是克隆它:

int[] clone = (int[]) intArray.Clone();

If you really need to use Array.CopyTo then use the other answers - but otherwise, this route will be simpler :) 如果你真的需要使用Array.CopyTo然后使用其他答案 - 但否则,这条路线会更简单:)

This works: 这有效:

int[] intArray = new int[] { 10, 34, 67, 11 };
Array copyArray = Array.CreateInstance(typeof(int), intArray.Length);
intArray.CopyTo(copyArray, 0);
foreach (var i in copyArray)
    Console.WriteLine(i);

You had one extra "intArray" in your Array.CreateInstance line. 您在Array.CreateInstance行中有一个额外的“intArray”。

That being said, this can be simplified if you don't need the Array.CreateInstance method (not sure if that's what you're trying to work out, though): 话虽如此,如果您不需要Array.CreateInstance方法(不确定这是否是您尝试解决的问题),这可以简化:

int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = new int[intArray.Length];
intArray.CopyTo(copyArray, 0);

Even simpler: 更简单:

int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = (int[])intArray.Clone();

Try this instead: 试试这个:

int[] copyArray = new int[intArray.Length];
Array.Copy(intArray, copyArray, intArray.Length);

在这种特殊情况下,只需使用

int[] copyArray = (int[]) intArray.Clone();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM