1.数组的声明和初始化
int[] arr = new int[3];
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
或者
int[] arr = new int[]{0,1,2};
2.数组的访问:
foreach(int i in arr)
Console.WriteLine(i); //不能对i进行赋值
或者
for(int i=0;i<arr.Length,i++)
Console.WriteLine(arr[i]);
3.动态数组
C#不支持动态数组,但是,我们可以自己创建动态数组。
class Array
{
public static void CreateArray(out int[] arr, int length)
{
arr = new int[length];
foreach(int i in arr)
i = 1;
}
}
但是,可以通过使用ArrayList来实现。
a.必须使用System.Collections命名空间
b.ArraayList对象是较为复杂的数组,ArrayList类提供了Array类没有提供的一些功能。
c.Array VS ArrayList
----Array的容量固定,而ArrayList的容量可以根据需要自动扩充。
----ArrayList提供了添加、插入或者移除某一个范围的元素。而Array自能一次获取或者设置一个元素的值。
----Array可以具有多个维度,而ArrayList始终是一维的。
例如:从控制台输入字符串存到ArrayList中。
Using System.collections;
string str;
ArrayList arrlst = new ArrayList();
while (true)
{
Console.WriteLine("Please Add a string to ArrayList:");
str = Console.ReadLine();
if ("end" == str) break;
arrlst.Add(str);
for (int i = 0; i < arrlst.Count; i++)
Console.Write("{0} ",arrlst[i]);
Console.WriteLine('/n');
}
4.多维数组的声明和使用
int[,] a2; //定义变量
int[,] a2 = new int[2,3];
int[,] a2 = new int[,]{{1,2,3},{4,5,6}}; //初始化
5.数组的数组(不规则数组)
int[][] j2;
int[][]j2 = new int[3][];
j2[0] = new int[]{1,2,3};
j2[1] = new int[]{1,2,3,4,5};
j2[2] = new int[]{1,2,3,4,5,6,7};