2009-05-19 62 views

回答

1

您還可以使用new操作也跟其他的對象類型:

int[] array = new int[5]; 

,或者用一個變量:

int[] array = new int[someLength]; 
8

首先製作一個數組列表。添加/刪除項目。然後ArrayList.ToArray()

還有你的陣列!

3
object foo = Array.CreateInstance(typeof(byte), length); 
21

我想添加到Natrium的答案,即泛型集合也支持這個.ToArray()方法。

List<string> stringList = new List<string>(); 
stringList.Add("1"); 
stringList.Add("2"); 
stringList.Add("3"); 
string[] stringArray = stringList.ToArray(); 
+1

需要注意的是,它們支持ToArray(),因爲在內部,list只是使用一個不可變數組,並根據需要使用新的分配來增加它。 – 2014-12-07 10:50:59

4

好吧所以數組初始化讓我每次。所以我花了10分鐘來做這件事。

static void Main(string[] args) 
    { 
     String[] as1 = new String[] { "Static", "with", "initializer" }; 
     ShowArray("as1", as1); 

     String[] as2 = new String[5]; 
     as2[0] = "Static"; 
     as2[2] = "with"; 
     as2[3] = "initial"; 
     as2[4] = "size"; 
     ShowArray("as2", as2); 

     ArrayList al3 = new ArrayList(); 
     al3.Add("Dynamic"); 
     al3.Add("using"); 
     al3.Add("ArrayList"); 
     //wow! this is harder than it should be 
     String[] as3 = (String[])al3.ToArray(typeof(string)); 
     ShowArray("as3", as3); 

     List<string> gl4 = new List<string>(); 
     gl4.Add("Dynamic"); 
     gl4.Add("using"); 
     gl4.Add("generic"); 
     gl4.Add("list"); 
     //ahhhhhh generic lubberlyness :) 
     String[] as4 = gl4.ToArray(); 
     ShowArray("as4", as4); 
    } 

    private static void ShowArray(string msg, string[] x) 
    { 
     Console.WriteLine(msg); 
     for(int i=0;i<x.Length;i++) 
     { 
      Console.WriteLine("item({0})={1}",i,x[i]); 
     } 
    } 
-1
int[] array = { 1, 2, 3, 4, 5}; 

for (int i=0;i<=array.Length-1 ;i++) { 
    Console.WriteLine(array[i]); 
}