2017-03-15 60 views
-1

我搜索,但沒有找到在C#鐵血陣列通過聲明數組

我已經宣佈和分配陣列的解決方案:

string[] arr1 = {"a","b","c","d","e","f"}; 
string[] arr2 = {"1","2","3","4","5","6"}; 
string[] arr3 = {"s","t","a","c","k","o"}; 
string[] arr4 = {"v","e","r","f","l","w"}; 

我要讓那些陣列交錯數組,但沒有成功。

string[,] port = new string[] 
{ 
    new string[] arr1[], 
    new string[] arr2[], 
    new string[] arr3[], 
    new string[] arr4[], 
}; 

我犯的錯誤在哪裏?

我的計劃會產生隨機int s到來自鋸齒狀排列調用值

Random random = new Random(); 
int x = random.Next(0,5); 
int y = random.Next(0,3); 
Console.WriteLine(port[y,x]); 
+0

你想創建一個數組的數組? – mm8

+0

是的,但我做不到,它是一種2維數組,我怎麼需要從聲明的數組中創建該數組 – melic

+0

簡而言之,[[,]'是多維的,[] []是鋸齒的 – Slai

回答

1

有兩種錯誤:

  1. 你不聲明鋸齒狀陣列,但多維一。由於你的「內部」數組已經定義好了,所以你需要一個陣列這就是所謂的「鋸齒狀」陣列。
  2. 你不需要new string[]在聲明中,你已經聲明內陣列

所以這應該工作:

string[][] port = new string[][] 
{ 
    arr1, arr2, arr3, arr4 
}; 

或數組初始化更短:

string[][] port = { arr1, arr2, arr3, arr4 }; 

要訪問此數組,請使用:

Console.WriteLine(port[y][x]); 
+0

似乎我不明白的鋸齒陣列的邏輯;謝謝它的工作 – melic

1

試試這個:

string[] arr1 = { "a", "b", "c", "d", "e", "f" }; 
string[] arr2 = { "1", "2", "3", "4", "5", "6" }; 
string[] arr3 = { "s", "t", "a", "c", "k", "o" }; 
string[] arr4 = { "v", "e", "r", "f", "l", "w" }; 

string[][] port = new string[4][]; 
port[0] = arr1; 
port[1] = arr2; 
port[2] = arr3; 
port[3] = arr4; 

或者乾脆:

string[][] port = new string[][] { arr1, arr2, arr3, arr4 }; 

用法:

string test = port[1][5]; 
+0

謝謝mm8,它是非常好的,你一次分享2解決方案 – melic

+0

我希望我能接受這兩個答案:D你們兩個幫了我很多 – melic