int[,] arr1 = { {1,2,3}, {4,5,6} };
int[,] arr2 = new int[2,3] { {1,2,3}, {4,5,6} };
int[,] arr3 = new int[,] { {1,2,3}, {4,5,6} };
int[,] arr = new int[5,4];
foreach (int i in arr) // 注意:foreach 取得的是元素值,無法直接賦值
{
// 正確寫法需用 for 迴圈索引
for (int r = 0; r < arr.GetLength(0); r++)
for (int c = 0; c < arr.GetLength(1); c++)
arr[r,c] = 0;
}
原文 foreach 寫法有誤,此處修正為索引賦值。
陣列實為 System.Array 實例,提供實用靜態方法:
Array.Reverse(arr):反轉元素順序。Array.Sort(arr):排序 (需元素實作 IComparable)。using System;
public class ArrayMethods
{
static void Main()
{
string[] names = new string[5];
Console.WriteLine("Enter five employee names:");
for (int i=0;i<5;i++) names[i] = Console.ReadLine();
Console.WriteLine("\n** Original **");
foreach (string n in names) Console.Write(n + " ");
Array.Reverse(names);
Console.WriteLine("\n\n** Reversed **");
foreach (string n in names) Console.Write(n + " ");
Array.Sort(names);
Console.WriteLine("\n\n** Sorted **");
foreach (string n in names) Console.Write(n + " ");
}
}
Enter five employee names:
Luca
Angie
Brian
Kent
Beatriz
** Original **
Luca Angie Brian Kent Beatriz
** Reversed **
Beatriz Kent Brian Angie Luca
** Sorted **
Angie Beatriz Brian Kent Luca