一般形式的陣列
C# 陣列是零值索引,也就是陣列索引是從零起始,當宣告一個陣列時,型別之後必須接著方括號 ([]),而不是識別項。

int[] table; // not int table[];

 

另一個要注意的細節是,如同在 C 語言中,陣列的大小並不是其型別的一部份。這可讓您能宣告一個陣列並指派任何的 int 物件陣列給它,不論陣列的長度。


int[] numbers; // declare numbers as an int array of any size

numbers = new int[10]; // numbers is a 10-element array

numbers = new int[20]; // now it's a 20-element array

 


C# 支援一維陣列、多維度陣列 (矩形陣列) 和陣列的陣列 (不規則陣列,Jagged Array)。


一維陣列:
int[] numbers;

多維度陣列:
string[,] names;

陣列的陣列 (不規則的):
byte[][] scores;

 實際上並未建立該陣列。在 C# 中,陣列為物件 ,並且必須具現化(在C#宣告一個變數使用都需要將該變數具現化,使用new)。下列範例介紹如何建立陣列:

一維陣列:
int[] numbers = new int[5];

多維度陣列:
string[,] names = new string[5,4];

陣列的陣列 (不規則的):
byte[][] scores = new byte[5][];

for (int x = 0; x < scores.Length; x++)

{

scores[x] = new byte[4];

}

您也可以有較大的陣列。例如,您可以有一個三維矩形陣列:
int[,,] buttons = new int[4,5,3];

至可以混合矩形和不規則陣列
int[][,,][,] numbers;

 

下列是宣告和具現化上述陣列的完整 C# 程式。


using System;
class DeclareArraysSample
{
    public static void Main()
    {
        // Single-dimensional array
        int[] numbers = new int[5];


        // Multidimensional array
        string[,] names = new string[5,4];


        // Array-of-arrays (jagged array)
        byte[][] scores = new byte[5][];


        // Create the jagged array
        for (int i = 0; i < scores.Length; i++)
        {
            scores[i] = new byte[i+3];
        }


        // Print length of each row
        for (int i = 0; i < scores.Length; i++)
        {
            Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
        }
    }
}

輸出結果:

Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7

 

資料來源:http://msdn.microsoft.com/zh-tw/library/aa288453(v=vs.71).aspx

arrow
arrow
    全站熱搜

    東勢厝滴yang 發表在 痞客邦 留言(0) 人氣()