一、声明格式
一维数组声明格式: <Type>[] <name>;多维数组声明格式: <baseType>[,] <name>;交错数组声明格式: <Type>[][] <name>;
二、初始化方式
一般数组初始化的两种方式:(1)完整的指定数组的内容。 int[] intArray = {1, 2, 3, 4, 5};
double[,] doubleArray = {{1, 2, 3, 4}, {2, 3, 4, 5}, {2, 4, 5 ,6}};(2)指定数组的长度,并使用new关键字初始化所有的数组元素 int[] intArray = new int[5]{1, 2, 3, 4, 5};
交错数组初始化的两种方式:(1)可以先初始化第一维的数组,然后再初始化它所包含的数组。 int[][] intArray; intArray = new int[2][]; intArray[0] = new int[3]; intArray[1] = new int[4];(2)使用下面的速记格式。注意:不能从元素初始化中省略new运算符,因为不存在元素的默认初始化。 intArray = new int[3][]{new int[]{1, 2, 3}, new int[] {1}, new int[] {1, 2});
三、特别注意
1)数值数组元素的默认值为0,引用元素的默认值为null。
2)交错数组是元素为数组的数组,故它的元素是引用类型,初始化为null。3)交错数组的元素的维度和大小可以不同。4)交错数组的维数是一维的,不管你定义为几维的。
5)数组的索引从0开始。
6)数组元素可以是任何类型,包括数组类型。
7)数组类型是从基类型Array派生的引用类型。
四、实例说明
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArrayApplication { class Program { static void Main(string[] args) { Console.WriteLine("一维数组的使用"); //数组的初始化的两种方式 //string[] friendNames = {"Adam Li", "Mike Xu", "Jerry Zhang"}; //完整的指定数组的内容 string[] friendNames; friendNames = new string[3] { "Adam Li", "Mike Xu", "Jerry Zhang" }; //指定数组的长度,并使用new关键字初始化所有的数组元素 Console.WriteLine("Here are {0} of my friends:", friendNames.Length); //输出数组的内容 /*for (int i = 0; i < friendNames.Length; i++) { Console.WriteLine(friendNames[i]); }*/ foreach (string tmpName in friendNames) { Console.WriteLine(tmpName); } Console.WriteLine("/n多维数组的使用"); double[,] hillHeight = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 } }; Console.WriteLine("The rank of the hillHeight:{0}", hillHeight.Rank); Console.WriteLine("The elements list:"); int k = 0; foreach (double hr in hillHeight) { k++; Console.Write("{0} ", hr); if (k % 4 == 0) { Console.WriteLine(); } } Console.WriteLine("/n交错数组的使用"); /*int[][] divisors1To10 = { new int[]{1}, new int[]{1, 2}, new int[]{1, 2, 3}, new int[]{1, 2, 3, 4}, new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5, 6}, new int[]{1, 2, 3, 4, 5, 6, 7}, new int[]{1, 2, 3, 4, 5, 6, 7, 8}, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} };*/ int[][] divisors1To10 = new int[10][] { new int[]{1}, new int[]{1, 2}, new int[]{1, 2, 3}, new int[]{1, 2, 3, 4}, new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5, 6}, new int[]{1, 2, 3, 4, 5, 6, 7}, new int[]{1, 2, 3, 4, 5, 6, 7, 8}, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} }; //打印交错数组的维数 Console.WriteLine("The rank of the divisors1To10:{0}", divisors1To10.Rank); foreach (int[] divisorsOfInt in divisors1To10) { foreach (int divisor in divisorsOfInt) { Console.Write("{0} ", divisor); } Console.WriteLine(); } Console.ReadKey(); } } }
输出结果: