2014-03-05 37 views
1

我想要創建一個ArrayList,其中我將存儲描述MP3播放器的結構,並且我想要訪問for循環內的所有參數,以便我可以在Console中打印這些參數。從結構的ArrayList獲取參數

我的問題是訪問for循環內的參數,任何人都可以指向正確的方向嗎?

另外這是家庭作業,所以arraylist和結構是必要的。

static public void mp3speler() 
    { 

     mp3 speler1 = new mp3(1, 1, "a", "b", "c"); 
     mp3 speler2 = new mp3(2, 1, "a", "b", "c"); 
     mp3 speler3 = new mp3(3, 1, "a", "b", "c"); 
     mp3 speler4 = new mp3(4, 1, "a", "b", "c"); 
     mp3 speler5 = new mp3(5, 1, "a", "b", "c"); 

     ArrayList mp3Array = new ArrayList(); 
     mp3Array.Add(speler1); 
     mp3Array.Add(speler2); 
     mp3Array.Add(speler3); 
     mp3Array.Add(speler4); 
     mp3Array.Add(speler5); 


     for (int i = 0; i < mp3Array.Count; i++) 
     { 
      string placeHolder = "0"; //= ((mp3)mp3Array[0].ID); 
      Console.WriteLine(@"MP3 Speler {0} 
Make: {1} 
Model: {2} 
MBSize: {3} 
Price: {4}", placeHolder, placeHolder, placeHolder, placeHolder, placeHolder); 
     } 
    } 

    struct mp3 
    { 
     public int ID, MBSize; 
     public string Make, Model, Price; 

     public mp3(int ID, int MBSize, string Make, string Model, string Price) 
     { 
      this.ID = ID; 
      this.MBSize = MBSize; 
      this.Make = Make; 
      this.Model = Model; 
      this.Price = Price; 
     } 
    } 
+1

'的ArrayList'結構?不要這樣做。使用'列表'避免裝箱/取消裝箱。 –

+0

'struct'?可變'結構'??請讓你的生活更輕鬆,並將'struct mp3'更改爲'class Mp3Player' ......或者至少閱讀「類和C#中的結構」一文。 –

+0

也不會將字段暴露爲'public',您應該將其轉換爲屬性 –

回答

4
  1. 使用通用List<T>,而不是ArrayList。它會阻止你的結構在每次添加或從集合中獲取物品時進行裝箱/拆箱。

    List<mp3> mp3List = new List<mp2>(); 
    mp3List.Add(speler1); 
    mp3List.Add(speler2); 
    mp3List.Add(speler3); 
    mp3List.Add(speler4); 
    mp3List.Add(speler5); 
    
  2. 使用索引訪問來自List<T>上給出的指標得到項目:

    for (int i = 0; i < mp3List.Count; i++) 
    { 
        Console.WriteLine(@"MP3 Speler {0} Make: {1} Model: {2} MBSize: {3} Price: {4}", 
         mp3List[i].ID, mp3List[i].Make, mp3List[i].Model, mp3List[i].MbSize, mp3List[i].Price); 
    } 
    
  3. 你也可以使用foreach代替for

    foreach (var item in mp3List) 
    { 
        Console.WriteLine(@"MP3 Speler {0} Make: {1} Model: {2} MBSize: {3} Price: {4}", 
         item.ID, item.Make, item.Model, item.MbSize, item.Price); 
    } 
    
+0

+1。我假設你也會顯示'foreach'版本...... –