c#集合

System.Collections 

概述

该命名空间下的.NET非泛型集合类如下所示:
— System.Collections.ArrayList:数组集合类,使用大小可按动态增加的数组实现Ilist接口。
— System.Collections.BitArray:布尔集合类,管理位值的压缩数组,该值为布尔值。
— System.Collections.Queue:队列,表示对象的先进先出集合。
— System.Collections.Stack:堆栈,表示对象的简单的后进先出集合。
— System.Collections.Hashtable:哈希表,表示键/值对的集合,这些键/值对根据键的哈希代码进行组织
— System.Collections.SortedList:排序集合类,表示键/值对的集合,这些键和值按键排序并可按键和索引访问。

该命名空间下的.NET非泛型接口如下所示:
— System.Collections.IEnumerator:支持在集合上进行简单迭代,可以迭代集合中的项。支持在非泛型集合进行简单迭代。
— System.Collections.ICollection:(继承于IEnumerable)定义所有集合的大小,枚举器和同步方法,可以获取集合中项的个数,并能把项复制到一个简单的数组类型中。
— System.Collections.IList:(继承于IEnumerable 和 ICollection)表示可按照索引单独访问一组对象,提供集合的项列表,并可以访问这些项。
— System.Collections.IDictionary:(继承于IEnumerable 和 ICollection)表示键/值对的集合
— System.Collections.IComparer:比较两个对象的方法
— System.Collections.IDictionaryEnumerator:枚举字典的元素

System.Collections名称空间中的“内置”集合划分成了三种类别:
有序集合:仅仅实现ICollection接口的集合,在通常情况下,其数据项目的插入顺序控制着从集合中取出对象的的顺序。 System.Collections.Stack和 System.Collections.Queue类都是ICollection集合的典型例子。
索引集合:实现Ilist的集合,其内容能经由从零开始的数字检索取出,就象数组一样。System.Collections.ArrayList对象是索引集合的一个例子。
键式集合:实现 IDictionary 接口的集合,其中包含了能被某些类型的键值检索的项目。IDictionary集合的内容通常按键值方式存储,可以用枚举的方式排序检索。 System.Collections.HashTable类实现了IDictionary 接口。

接口


IEnumerable

公开枚举数,该枚举数支持在非泛型集合上进行简单迭代
枚举数是循环访问其关联集合的对象。它可被视作指向集合中任何元素的可移动的指针。一个枚举数只能与一个集合关联,但一个集合可以具有多个枚举数

c#中的迭代器
public interface IEnumerator
{
    bool MoveNext();
    Object Current {get; }
    void Reset();
}

IEnumerable用于返回迭代器
public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

ICollection

继承自IEnumerable,可以返回集合中的元素数,可以使用copyTo方法copy数组,还有同步方法(这个没懂)


IList

继承自ICollection,IEnumerable


IDictionary

继承自ICollection,IEnumerable


定义集合类

把一个类定义为集合类,就可以对这个类的集合统一处理(比如foreach),所以定义集合类解决了统一处理某一类对象的问题。
但是为每个类单独定义集合类就会搞出很多个继承自集合类的类,而泛型的出现解决了这个问题。(一般不用自定义集合类,下面的例子有利于理解泛型)
CollectionBase类有接口IEnumerable,ICollection,和IList
List属性可以通过Ilist接口访问项目,InnerList属性用于存储项目的ArrayList对象
public class A:CollectionBase
{
	public void Add(A newA)
	{
		List.Add(newA);
	}

	public void Remove(A oldA)
	{
		List.Remove(oldA);
	}
	
...
	//索引符
	public A this(int aIndex)
	{
		get
		{
			return (A)List[aIndex];
		}
		set
		{
			List[aIndex]=value;
		}
	}
}

类似的有DictionaryBase
public class D:DictionaryBase
{
	public void Add(string newID,D newD)
	{
		Dictionary.Add(newID,newD);
	}

	public void Remove(string oldID)
	{
		Dictionary.Remove(oldID)
	}
	
	public D this[string dID]
	{
		get
		{
			return (D)Dictionary[dID];	
		}
		set
		{
			Dictionary[dID] = value;
		}
	}
}



常用集合类

ArrayList

也执行IList,ICollection和IEnumerable接口,但与数组不同,它是大小可变的

跟数组一样是连续内存存储,ArrayList中存的是Object所以可以存入不同类型的对象



posted @ 2014-10-23 22:12  00000000O  阅读(131)  评论(0编辑  收藏  举报