数组

定义数组

1 int[] test1;  //定义一个新数组
2 test1 = new int[10];   //定义数组长度(此时所有元素都是0)
3 
4 int[] test2 = new int[] { 1, 2, 3, 4, 5, 6 };  //也可以直接定义元素
1 int[] intArry = Array.CreateInstance(typeof(int), 10) as int[]; //(类型,长度)

数组之间的拷贝

1 //(原数组,原数组开始拷贝索引,新数组,新数组开始拷贝索引,拷贝元素个数)
2 Array.Copy(intArry, 3, intArry2, 4, intArry.Length-4); //数组的拷贝

矩形数组

int[,] IntList6 = new int[3, 4]{ {1,2,3,4 },{2,3,4,5},{3,4,5,6} }; //定义二维数组

其形状为:

[0,0] [0,1] [0,2]
[1,0] [1,1] [1,2]
[2,0] [2,1] [2,2]
[3,0] [3,1] [3,2]

 

 

 

 

当使用foreach进行访问时

会依次按照[0,0][0,1]...[1,0][1,1]...[3,4]进行访问

锯齿数组

锯齿数组不能采取如下方式定义

int[][] a = new int[3][4];  //错误

可以进行依次初始化

//第一种
a = new int[3][];
//第二种
a[0] = new int[1];
a[1] = new int[2];
a[2] = new int[2];
a[3] = new int[3];

或直接赋值

int[][] List1 =
{
    new int[] { 1},
    new int[] { 1,2,},
    new int[] {1,3},
    new int[] {1,2,4},
    new int[] {1,5},
    new int[] {1,2,3,6}
}; 

锯齿数组不能直接使用foreach循环进行访问

因为其内部元素为int[]而不是int

所以应当如此:

foreach(int[] list in List1)
{//必须先遍历每个子集在遍历每个元素
    foreach(int i in list)
    {
        Console.WriteLine(i);
    }
}
posted @ 2018-09-25 12:46  邢韬  阅读(208)  评论(0编辑  收藏  举报