C# Array 数组

部分参考或转载:菜鸟教程–数组(Array)

1 数组声明与初始化

1.1 数组声明

如:int[] arr;// 数据类型 [] 数组名

1.2 初始化数组

  数组是一个引用类型,所以您需要使用 new 关键字来创建数组的实例。
1)使用new 关键字创建数组实例
double[] arr = new double[10];
2)①动态初始化[定义与赋值操作分开进行]
      例1:int[] arr = new int[10]; arr[0] =1;arr[1] =3;arr[2] =2;
      例2:MyData []data;data = new MyData[3];
               data[0] = new MyDate(22,7,1964);
               data[1] = new MyDate(1,1,2000);

      ②静态初始化[定义和赋值操作同时进行]
      例1:int[] a = { 3, 9, 8};
               也可写为: int[] a = new int[]{ 3, 9,8 };
      例2:MyDate[] dates= { new MyDate(22, 7, 1964), new MyDate(1, 1, 2000), new MyDate(22, 12, 1964) };

2 访问数组元素

2.1 通过索引访问

int[] n = new int[5];
for(int i=0;i<5;i++)
{
	n[i] = i;
}
for(int j=0;j<n.Length;j++)
{
	Console.WriteLine(n[j]);
}

2.2 使用foreach访问

①foreach可以方便地处理数组、集合中各元素。[foreach是只读式的遍历]。
例如:

int [] ages = new int []{1,2,3,4,5};
foreach( int age in ages)
{
	......
} 

3 多维数组

①二维数组举例:int [,] a = {{1,2,5},{3,4,0},{5,6,7}};
②可以用 a.GetLength(0) , a.GetLength(1) 来获得各个维度的长度

4 交错数组

形如:
int [][] t = new int [3][];
t[0] = new int[2];t[1] = new int[4];t[2] = new int[3];

猜你喜欢

转载自blog.csdn.net/qq_29406323/article/details/86303479