数组是一个用来存储相同类型数据的、固定大小的、具有连续内存位置的顺序集合。数组中的每个元素都对应一个索引值,索引从 0 开始依次递增,我们可以通过索引来访问数组中的指定元素。
所有数组都是由连续的内存位置组成,最低的内存地址对应第一个元素,最高的内存地址对应最后一个元素,如下图所示:
![](https://img-blog.csdnimg.cn/img_convert/61de1d93d06999fdd2013aea9e70d20c.gif)
一.声明数组
data_type[]data_type
data_type用来指定数组的类型,[]用来声明数组的维度,data_type声明数组的名称
例: int[]a1 //声明一个名为a1的整型数组
double[]a2 //声明一个名为a2的浮点型数组
二.初始化数组
数组只有经过初始化才能为其中的元素进行赋值,
数组是引用类型的,需要使用new对数组进行初始化
例:
int[]a1 //声明一个整型数组
a1=new int[10] // 初始化数组a1
数组的声明和初始化可以放在一起进行
例:
int []a1=new int[10]
三:访问数组中的元素
通过数组的索引(下标)来访问数组中指定元素
四:使用foreach遍历数组
using System;
namespace c.shuzu
{
class shuzu1
{
static void Main(string[] args){
int[] a = new int[]{100, 101, 102, 103, 104, 105, 106, 107, 108, 109};
int count = 0;
foreach(int i in a){
Console.WriteLine("a[{0}] = {1}", count, i);
count++;
}
Console.ReadLine();
}
}
}
运行结果
a[0] = 100
a[1] = 101
a[2] = 102
a[3] = 103
a[4] = 104
a[5] = 105
a[6] = 106
a[7] = 107
a[8] = 108
a[9] = 109
![](https://img-blog.csdnimg.cn/img_convert/8da90179f4a6fe9867a6f0e094ecd3bf.png)