2014-03-05 39 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'版本...... –