Skip to main content
 首页 » 编程设计

c#之从结构体的 ArrayList 获取参数

2024年02月13日13mate10pro

我想创建一个数组列表,我将在其中存储描述 mp3 播放器的结构,我想在 for 循环中访问所述参数,以便我可以在控制台中打印这些参数。

我的问题是访问 for 循环内的参数,谁能指出正确的方向?

这也是作业,所以arraylist和struct是必须的。

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. 使用通用 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); 
     }