C#学习笔记—数组
1、C#数组初始化语法
View Code
1 static void ArrayInitialization()
2 {
3 //使用new关键字的数组初始化语法
4 string[] stringArray = new string[] { "one", "two", "three" };
5 Console.WriteLine("stringArray has {0} elements", stringArray.Length);
6 //你使用new关键字的数组初始化方法
7 bool[] boolArray = { false, false, true };
8 Console.WriteLine("boolArray has {0} elements", boolArray.Length);
9 }
2、隐式类型本地数组
View Code
1 static void DeclareImplicitArrays()
2 {
3 //a 实际上是int[]
4 var a = new[] { 1, 100, 10, 1000 };
5 Console.WriteLine("a is a: {0}", a.ToString());
6 //b实际上是string[]
7 var c = new[] { "hello", null, "world" };
8 Console.WriteLine("c is a: {0}", c.ToString());
9 Console.WriteLine();
10 }
3、定于object数组
View Code
1 static void ArrayOfObjects()
2 {
3 //对象数组可以是任何东西
4 object[] myObjects = new object[4];
5 myObjects[0] = 10;
6 myObjects[1] = false;
7 myObjects[2] = new DateTime(2012,11, 11);
8 myObjects[3] = "string";
9
10 foreach (object obj in myObjects)
11 {
12 Console.WriteLine("Type:{0}, Value:{1}", obj.GetType(), obj);
13 }
14 Console.WriteLine();
15 }
4、矩形多维数组
View Code
1 static void RectMultidimensionalArray()
2 {
3 //矩形多维数组
4 int[,] myMatrix = new int[6,6];
5 //填充6×6数组
6 for (int i = 0; i < 6; i++)
7 for (int j = 0; j < 6; j++)
8 myMatrix[i, j] = i * j;
9 //输出6×6数组
10 for (int i = 0; i < 6; i++)
11 {
12 for (int j = 0; j < 6; j++)
13 Console.Write(myMatrix[i, j] + "\t");
14 Console.WriteLine();
15 }
16 Console.WriteLine();
17 }
5、交错多维数组
View Code
1 static void JaggedMultidimensionalArray()
2 {
3 //交错多维数组,声明一个具有5个不同数组的数组
4 int[][] myJagArray = new int[5][];
5
6 //创建交错数组
7 for (int i = 0; i < myJagArray.Length; i++)
8 myJagArray[i] = new int[i + 7];
9 //输出每一行
10 for (int i = 0; i < 5; i++)
11 {
12 for (int j = 0; j < myJagArray[i].Length; j++)
13 Console.Write(myJagArray[i][j] + " ");
14 Console.WriteLine();
15 }
16 Console.WriteLine();
17 }
6、数组作为参数
View Code
1 static void PrintArray(int[] myInts)
2 {
3 for (int i = 0; i < myInts.Length; i++)
4 Console.WriteLine("Item {0} is {1}", i, myInts[i]);
5 }
6
7 static string[] GetStringArray()
8 {
9 string[] theStrings = { "Hello", "from", "GetStringArray"};
10 return theStrings;
11 }
12
13 static void PassAndReceiveArrays()
14 {
15 //传递数组作为参数
16 int[] ages = { 20, 22, 23, 0 };
17 PrintArray(ages);
18
19 //获取数组作为返回值
20 string[] strs = GetStringArray();
21 foreach (string s in strs)
22 Console.WriteLine(s);
23
24 Console.WriteLine();
25 }
7、System.Array基类
Clear():这个静态方法将数组中一系列元素设置为空值
CopyTo():这个方法用来将原数组中的元素复制到目标数组中
Length: 这个属性返回数组中项的个数
Rank:这个属性返回当前数组维数
Reverse():这个静态方法反转一维数组的内容
Sort():这个静态方法为内建类型的一维数组排序。如果数组中的元素实现IComparer接口,就可以为自定义类型排序。