# 陣列Arrays

## 陣列型別Array types

array_type
: non_array_type rank_specifier+
;

non_array_type
: type
;

rank_specifier
: '[' dim_separator* ']'
;

dim_separator
: ','
;


A non_array_type可以是任何型別也就是本身並非array_typeA non_array_type is any type that is not itself an array_type.

• 陣列類型的表單T[R]是陣列陣序規範R和非陣列元素型別TAn array type of the form T[R] is an array with rank R and a non-array element type T.
• 陣列類型的表單T[R][R1]...[Rn]是陣列陣序規範R和 項目類型T[R1]...[Rn]An array type of the form T[R][R1]...[Rn] is an array with rank R and an element type T[R1]...[Rn].

### 陣列和泛型 IList 介面Arrays and the generic IList interface

using System.Collections.Generic;

class Test
{
static void Main() {
string[] sa = new string;
object[] oa1 = new object;
object[] oa2 = sa;

IList<string> lst1 = sa;                    // Ok
IList<string> lst2 = oa1;                   // Error, cast needed
IList<object> lst3 = sa;                    // Ok
IList<object> lst4 = oa1;                   // Ok

IList<string> lst5 = (IList<string>)oa1;    // Exception
IList<string> lst6 = (IList<string>)oa2;    // Ok
}
}


## 陣列共變數Array covariance

class Test
{
static void Fill(object[] array, int index, int count, object value) {
for (int i = index; i < index + count; i++) array[i] = value;
}

static void Main() {
string[] strings = new string;
Fill(strings, 0, 100, "Undefined");
Fill(strings, 0, 10, null);
Fill(strings, 90, 10, 0);
}
}


## 陣列初始設定式Array initializers

array_initializer
: '{' variable_initializer_list? '}'
| '{' variable_initializer_list ',' '}'
;

variable_initializer_list
: variable_initializer (',' variable_initializer)*
;

variable_initializer
: expression
| array_initializer
;


int[] a = {0, 2, 4, 6, 8};


int[] a = new int[] {0, 2, 4, 6, 8};


a = 0; a = 2; a = 4; a = 6; a = 8;


int[,] b = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};


int[,] b = new int[5, 2];


b[0, 0] = 0; b[0, 1] = 1;
b[1, 0] = 2; b[1, 1] = 3;
b[2, 0] = 4; b[2, 1] = 5;
b[3, 0] = 6; b[3, 1] = 7;
b[4, 0] = 8; b[4, 1] = 9;


int[,] c = {};


int[,] c = new int[0, 0];


int i = 3;
int[] x = new int {0, 1, 2};        // OK
int[] y = new int[i] {0, 1, 2};        // Error, i not a constant
int[] z = new int {0, 1, 2, 3};     // Error, length/initializer mismatch