这是最古老的集合,什么都能装(int, string, object...),但也最不安全。
using System.Collections;
ArrayList bag = new ArrayList();
bag.Add("打狗棒"); // 装字符串
bag.Add(100); // 装整数(这不安全!)
// 取出来的时候,必须强制转换
string weapon = (string)bag[0];
这是现在的江湖主流(泛型集合)。它规定了只能装特定类型的东西。
using System.Collections.Generic;
// 这是一个只装字符串的列表
List swords = new List();
swords.Add("倚天剑");
swords.Add("屠龙刀");
// swords.Add(123); // 报错!这里不能放数字,岳长老会拦住你。
// 它是动态的!
Console.WriteLine(swords.Count); // 2
swords.Remove("屠龙刀"); // 扔掉一把
Console.WriteLine(swords.Count); // 1
键值对(Key-Value)。通过一个线索(Key)找到宝藏(Value)。
Dictionary power = new Dictionary();
power.Add("令狐冲", 95);
power.Add("东方不败", 100);
Console.WriteLine(power["令狐冲"]); // 95
ArrayList 了,因为它性能差(涉及装箱拆箱)且不安全。
List<T> 和 Dictionary<K, V>,它们在 System.Collections.Generic 命名空间下。
创建一个 List<string>,把“风清扬”、“令狐冲”、“任盈盈”加进去。
然后遍历这个列表,如果名字包含“令”,就把它从列表中移除。
(提示:在遍历时移除元素是危险动作,最好用倒序遍历,或者用 RemoveAll)
List heros = new List { "风清扬", "令狐冲", "任盈盈" };
// 方法一:高手招式
heros.RemoveAll(name => name.Contains("令"));
// 方法二:笨办法(倒序循环)
// for (int i = heros.Count - 1; i >= 0; i--)
// {
// if (heros[i].Contains("令")) heros.RemoveAt(i);
// }
foreach (var h in heros) Console.WriteLine(h);