2016-06-15 161 views
1

我宣佈了一些數組,然後得到一個錯誤,說:」意外符號'{'「。C#數組錯誤「意想不到的符號」{'「

int[] array ; 

void Start() { 
    if (level == 1) { 
     array = { 1, 2, 3, 4, 5}; //error here 
    }else if (level == 2) { 
     array = { 1, 2, 3, 4, 5, 6, 7}; //error here 
    }else if (level == 3) { 
     array = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; 
    } 
} 

我上面的代碼更改爲這個

array [0] = 1; 
array [1] = 2; 
... 

,但我希望有一個簡單的辦法,如第一個代碼,怎麼樣?

+3

只要做'array = new [] {1,2,3,4,5};' – Habib

回答

6

您只能在聲明時使用上述語法,以後不能再使用它。

如果你想使用類似的東西比你可以這樣做:

array = new[] { 1, 2, 3, 4, 5}; 

array = new int[] { 1, 2, 3, 4, 5}; 

但是,在申報的時候,你可以這樣做:

int[] array = { 1, 2, 3, 4, 5 }; //this should compile fine 
1

你可以使用類似下面的東西:

array =new int[] { 1, 2, 3, 4, 5}; 

初始化數組

相關問題