数组的属性:
数组可以是一维、多维或交错的。
数值数组元素的默认值设置为零,而引用元素的默认值设置为 null。
交错数组是数组的数组,因此,它的元素是引用类型,初始化为 null。
数组的索引从零开始:具有 n 个元素的数组的索引是从 0 到 n-1。
数组元素可以是任何类型,包括数组类型。
数组类型是从抽象基类型 Array 派生的引用类型。由于此类型实现了 IEnumerable 和 IEnumerable,因此可以对 C# 中的所有数组使用 foreach 迭代。
我对数组的理解:在 C# 中,数组实际上是对象,而不只是像 C 和 C++ 中那样的可寻址连续内存区域
一维数组 :一维数组以线性方式存储固定数目的项,只需一个索引值即可标识任意一个项。
一维数组实例:
1
2
3
4
5
6
7
8
9
10
11
12
|
static
class
Program
{
static
void
Main()
{
//一维数组
int
[] arry =
new
int
[9] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
arry[0] = 2;
//第一行为2
Console.WriteLine(arry);
}
}
|
1
|
<br>
|
运行结果截图
二维数组实例
1
2
3
4
5
6
7
8
9
10
11
12
|
//二维数组
int
[,] arry2 =
new
int
[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
arry2[1, 0] = 5;
//改变第二列的第一行为5
for
(
int
i = 0; i < arry2.GetLength(1); i++)
{
for
(
int
y = 0; y < arry2.GetLength(1); y++)
//第一个for循环遍历二维数组的列,第二个for循环遍历二维数组的行
{
Console.Write(arry2[i, y]);
}
}
|
运行结果截图
交错数组实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
//交错数组
int
[][] arry3 =
new
int
[3][];
//交错数组必须指定下标的个数
arry3[0] =
new
int
[] { 0, 1, 2, 4 };
arry3[1] =
new
int
[] { 3, 4, 5, 6 };
arry3[2] =
new
int
[] { 4, 8, 9 };
for
(
int
x = 0; x < arry3.Length; x++)
{
for
(
int
z = 0; z < arry3[x].Length; z++)
{
Console.Write(arry3[x][z]);
}
Console.WriteLine();
//以inti的数组元素为准进行换行.
}
|
运行结果截图
C# 还提供 foreach 语句。该语句提供一种简单、明了的方法来循环访问数组的元素,看下面实例。
1
2
3
4
5
6
7
8
9
|
static
void
Main()
{
int
[] arry4=
new
int
[100];
foreach
(
int
a
in
arry)
{
Console.Write(arry);
}
}
|
运行结果截图
【完美世界 http://www.23cat.com/Contents_51864.html】
【戮仙 http://www.23cat.com/Book_51960.html】