25.ArrayList和foreach

一、 ArrayList:集合,(即数组列表)

  优点1ArrayList 是一个可动态维护长度的集合。弥补了数组的局限性;
  优点2ArrayList 可以放入任意类型的数据。

 1     //注:需要引入命名空间 using System.Collections;
 2     class Program
 3     {
 4         void MyArrayList()
 5         {
 6             //实例化ArrayList对象
 7             ArrayList list = new ArrayList();
 8             list.Add(22);
 9             list.Add(202);
10             list.Add(66);
11             //插入数据的方法
12             list.Insert(1,999);                              //在下标为1的位置上插入999
13 
14             //删除数据
15             //list.RemoveAt(1);                               //按下标删除
16             //list.Remove(66);                                //按对象删除
17 
18             //清除数据
19             //list.Clear();
20             for (int i = 0; i < list.Count; i++)             //在集合中不使用length,而使用Count
21             {
22                 Console.WriteLine(list[i]);
23             }
24         }     
25         static void Main(string[] args)
26         {
27             Program b = new Program();
28             b.MyArrayList();
29             Console.ReadKey();
30         }
31     }

 

二、 foreach 遍历数组

  优点:简洁方便;
  缺点:不能在循环体中修改或删除集合中的数据。

 1     class Program
 2     {
 3         void MyArrayList()
 4         {
 5             //实例化ArrayList对象
 6             ArrayList list = new ArrayList();
 7             list.Add(22);
 8             list.Add(202);
 9             list.Add(66);
10             //foreach跟for循环相比,有一个缺点:
11             //不能在循环体中修改或删除集合中的数据
12             foreach (var item in list)                //var:任何数据类型
13             {
14                 Console.WriteLine(item);
15             }
16         }
17         static void Main(string[] args)
18         {
19             Program b = new Program();
20             b.MyArrayList();
21             Console.ReadKey();
22         }
23     }

 

posted @ 2017-10-07 19:28  LiuChangwei  阅读(531)  评论(0编辑  收藏  举报