初始化
通過下面的任何一種方法,都可以在一行中創建、設置和初始化多維數組:
int[,] intArray = { {1,2,3},
{4,5,6} };
int[,] intArray = new int [2,3] { {1,2,3},
{4,5,6} };
int[,] intArray = new int [,] { {1,2,3},
{4,5,6} };
程序循環中的初始化
數組中所有的元素都可以使用嵌套的循環進行初始化,如下所示:
int[,] intArray = new int[5,4];
foreach (int i in intArray)
{
foreach (int j in intArray[])
{
j = 0;
}
}
System.Array 類
在 .Net 中,數組是作為 System.Array 類的實例實現的。此類提供了幾個有用的方法,例如 Sort() 和 Reverse()。
下面的程序說明了使用這幾個方法是多麼的容易。首先,我們使用 Array 類的 Reverse() 方法來使數組的元素反向,然後,我們使用 Sort() 方法對它們進行排序:
using System; public class ArrayMethods { public static void Main() { // Create string array of size 5 string[] EmployeeNames = new string[5]; Console.WriteLine("Enter five employee names:"); // Read 5 employee names from user for(int i=0;i<5;i++) { EmployeeNames[i]= Console.ReadLine(); } // Print the array in original order Console.WriteLine("\n** Original Array **"); foreach(string EmployeeName in EmployeeNames) { Console.Write("{0} ", EmployeeName); } //print the array in reverse order. Console.WriteLine("\n\n** Values in Reverse Order **"); System.Array.Reverse(EmployeeNames); foreach(string EmployeeName in EmployeeNames) { Console.Write("{0} ", EmployeeName); } //print the array in sorted order. Console.WriteLine("\n\n** Values in Sorted Order **"); System.Array.Sort(EmployeeNames); foreach(string EmployeeName in EmployeeNames) { Console.Write("{0} ", EmployeeName); } } }
下面是此程序的一些典型輸出:
Enter five employee names:
Luca
AngIE
Brian
Kent
Beatriz
** Original Array **
Luca AngIE Brian Kent Beatriz
** Values in Reverse Order **
Beatriz Kent Brian AngIE Luca
** Values in Sorted Order **
AngIE Beatriz Brian Kent Luca