System.Collections.Generics名称空间
List<T> 和 Dictionary<K, V>两种类型。
1. List<T>
List<T>泛型集合类型更加快捷、更易于使用;这样,就不必像上一章那样,从CollectionBase中派生一个类,然后实现需要的方法。
List<T> myCollection = new List<T>();
然后myCollection就可以调用以下的方法,非常简便。
int Count 该属性给出集合中项的个数
void Add(T item) 把一个项添加到集合中
void AddRange(IEnumerable<T>) 把多个项添加到集合中
IList<T> AsReadOnly() 给集合返回一个只读接口
int Capacity 获取或设置集合可以包含的项数
void Clear() 删除集合中的所有项
bool Contains(T item) 确定item 是否包含在集合中
void CopyTo(T[] array, int index) 把集合中的项复制到数组array 中,从数组的索引index 开始
IEnumerator<T> GetEnumerator() 获取一个IEnumerator<T>实例,用于迭代集合。注意,返回的接口强类型化为T,
所以在foreach 循环中不需要类型转换
int IndexOf(T item) 获取item 的索引,如果集合中并未包含该项,就返回−1
void Insert(int index, T item) 把item 插入到集合的指定索引位置上
bool Remove(T item) 从集合中删除第一个item,并返回true;如果item 不包含在集合中,就返回false
void RemoveAt(int index) 从集合中删除索引index 处的项
List<T>还有个Item 属性,允许进行类似于数组的访问,如下所示:
T itemAtIndex2 = myCollectionOfT[2];
例程:
static void Main( )
{
List<Animal> animalCollection = new List<Animal>(); ///List<T>用于普通类型的处理
animalCollection.Add(new Cow("Jack"));
animalCollection.Add(new Chicken("Vera"));
foreach (Animal myAnimal in animalCollection)
{
myAnimal.Feed();
}
Console.ReadKey();
}
2.Dictionary<K, V>
这个类型可以定义键/值对的集合。与本章前面介绍的其他泛型集合类型不同,这个类需要实例化两个类型,分别用于键和值,以表示集合中的各个项。
实例化Dictionary<K, V>对象后,就可以像在继承自DictionaryBase 的类上那样,执行相同的操作。
Dictionary<string, int> things = new Dictionary<string, int>();
things.Add("Green Things", 29);
使用Keys 和Values 属性迭代集合中的键和值:
foreach (string key in things.Keys)
{
Console.WriteLine(key);
}
foreach (int value in things.Values)
{
Console.WriteLine(value);
}
还可以迭代集合中的各个项,把每个项作为一个KeyValuePair<K, V>实例来获取:
首先定义KeyValuePair类,K和V都采用泛型,可兼容任何类型,以便日后使用。
foreach (KeyValuePair<string, int> thing in things)
{Console.WriteLine("{0} = {1}", thing.Key, thing.Value);
}