陣列 (C# 程式設計手冊)Arrays (C# Programming Guide)

您可以在陣列資料結構中儲存相同類型的多個變數。You can store multiple variables of the same type in an array data structure. 您可以指定陣列元素的類型來宣告陣列。You declare an array by specifying the type of its elements. 如果希望陣列存儲任何類型的元素,則可以指定object為其類型。If you want the array to store elements of any type, you can specify object as its type. 在 C# 的統一型別系統中,所有類型 (預先定義和使用者定義的、參考型別和實值型別) 都會直接或間接繼承自 ObjectIn the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

type[] arrayName;

範例Example

下列範例會建立一維陣列、多維陣列和不規則陣列︰The following example creates single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass
{
    static void Main()
    {
        // Declare a single-dimensional array of 5 integers.
        int[] array1 = new int[5];

        // Declare and set array element values.
        int[] array2 = new int[] { 1, 3, 5, 7, 9 };

        // Alternative syntax.
        int[] array3 = { 1, 2, 3, 4, 5, 6 };

        // Declare a two dimensional array.
        int[,] multiDimensionalArray1 = new int[2, 3];

        // Declare and set array element values.
        int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };

        // Declare a jagged array.
        int[][] jaggedArray = new int[6][];

        // Set the values of the first array in the jagged array structure.
        jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
    }
}

陣列概述Array overview

陣列具有下列屬性︰An array has the following properties:

  • 陣列可以是一維多維不規則An array can be Single-Dimensional, Multidimensional or Jagged.
  • 當陣列執行個體建立時,也會建立維度的數目和每個維度的長度。The number of dimensions and the length of each dimension are established when the array instance is created. 在執行個體的存留期期間,這些值無法變更。These values can't be changed during the lifetime of the instance.
  • 數值陣列元素的預設值設定為零,且參考元素會設定為 null。The default values of numeric array elements are set to zero, and reference elements are set to null.
  • 不規則陣列為陣列的陣列,因此其元素為參考類型,且會初始化為 nullA jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
  • 陣列為以零為基底索引:具有 n 個元素的陣列,會從 0n-1 編製索引。Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
  • 陣列元素可以是任何類型,包含陣列類型。Array elements can be of any type, including an array type.
  • 陣列類型是衍生自抽象基底類型 Array參考類型Array types are reference types derived from the abstract base type Array. 由於這個類型會實作 IEnumerableIEnumerable<T>,您可以在所有以 C# 撰寫的陣列上使用 foreach 反覆項目。Since this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.

C# 語言規格C# language specification

如需詳細資訊,請參閱c # 語言規格For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also