数组可以引用2个不同的数组

时间:2013-12-29 10:57:20

标签: c# arrays reference

让我说我有

int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];

无论如何通过引用将它们传递给一维数组?

int[] array = new int[21];

//Could I now make the arraySegment1 be passed in array[0] - array[10] by reference? 
//And arraySegment2 in array[11] - array[21] passed by reference?

//Then when executing:
array[0] = 10000000;

System.Console.WriteLine(arraySegment1[0]);

//It should display 10000000
//By putting the arraySegment1 as reference in the one dimensional array: array?

4 个答案:

答案 0 :(得分:3)

签出Array.Copy方法,该方法允许您将数组段复制到目标数组:

int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
// TODO: populate the arraySegment1 and arraySegment2 with some values

int[] array = new int[20];
Array.Copy(arraySegment1, 0, array, 0, arraySegment1.Length);
Array.Copy(arraySegment2, 0, array, arraySegment1.Length, arraySegment2.Length);

对于得到的数组,20也足够长,如果2个源数组各为10,则不是21。

答案 1 :(得分:1)

试试这个..

        int[] arraySegment1 = new int[10];
        int[] arraySegment2 = new int[10];
        int[] array = new int[21];
        arraySegment1.CopyTo(array,0);
        arraySegment2.CopyTo(array,(arraySegment1.Length));

答案 2 :(得分:0)

没有。标准阵列无法实现。但是使用泛型,你可以做这样的事情:

int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
// populate arrays

List<int[]> lists = new List<int[]>();
lists.Add(arraySegment1);
lists.Add(arraySegment2);

lists[0][0] = 100000;
System.Console.WriteLine(arraySegment1[0]); // then it will display 100000

答案 3 :(得分:-2)

你输错了对象

将写行中的arraySegment1更改为数组

System.Console.WriteLine(array[0]);