IEnumerable 接口公开枚举数,该枚举数支持在集合上进行简单迭代。IEnumerable和IEnumerator 接口实现IEnumerable接口的类型可以利用枚举对象支持对其项目的只向前访问,枚举对象为项目集提供只向前的只读指针IEnumerable接口有一个方法 GetEnumeratorpublic interface IEnumerable{ IEnumerator GetEnumerator();} 这个方法每次调用时返回一个枚举对象的新实例,返回的对象执行IEnumerator接口,这个方法可以用来顺序访问某个枚举类型所拥有的System.Object类型集
<script Language="C#" runat="server">
void Page_Load(Object sender, EventArgs args ) {
String[] authors = new String[] {"Richard","Alex","Dave","Rob","Brian","Karli"};
IEnumerator e; e = authors.GetEnumerator();
while (e.MoveNext() == true) { outResult.InnerHtml += e.Current + "<br />"; }
}</script>
所有的数组都可以执行IEnumerator接口,所以可以调用GetEnumerator方法,IEnumerator接口的Current属性定义为System.Object类型在.NET Framework类库中,其他所有的可枚举类型均从IEnumerable接口继承(其他的枚举类型为访问他们自身所包含的项目提供了额外的成员,也使用枚举对象来支持只前向光标方法) 所有其他的Enumerator接口也都是从IEnumerable接口派生。
IComparer 接口列表排序 IComparer 和 IComparable像ArrayList 和 Array这样的集合类使用System.Collections.IComparer 接口来确定类型实例的大小,该接口有一个方法public int Compare(Object x,Object y)公开一种比较两个对象的方法。此接口与 Array.Sort 和 Array.BinarySearch 方法一起使用。它提供一种自定义集合排序顺序的方法。
应用实例using System;
namespace Collection{ /// <summary> /// Person 的摘要说明。 /// </summary> /// public class Person { public int ID; public int Age;
public Person() { this.ID = 0; this.Age = 0; } public Person(int id,int age) { this.ID = id; this.Age = age; } public void Show() { System.Console.WriteLine("年龄={0},代号={1}",Age,ID); }
public static void ShowPersons(Person[] persons) { foreach(Person person in persons) { System.Console.WriteLine("年龄={0},代号={1}",person.Age,person.ID); } } }
public class PersonComparer:System.Collections.IComparer { int System.Collections.IComparer.Compare(object x,object y) { if (x == null || y == null) { throw new System.ArgumentException("参数不能为空"); }
Person temp = new Person(); if (!x.GetType().Equals(temp.GetType()) || !y.GetType().Equals(temp.GetType())) { throw new System.ArgumentException("类型不一致"); } Person personX = (Person)x; Person personY = (Person)y;
if (personX.ID > personY.ID) return 1; else if(personX.ID < personY.ID) return -1; else return 0;
} } /// <summary> /// Class1 的摘要说明。 /// </summary> class Class1 { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main(string[] args) { Random rand=new Random(); Person[] persons=new Person[6]; Console.WriteLine("随机产生的Person数组为:"); for(int i=0;i<persons.GetLength(0);i++) { persons[i] = new Person(); persons[i].ID = rand.Next(); persons[i].Age = rand.Next()P; persons[i].Show(); } PersonComparer personComparer=new PersonComparer(); Array.Sort(persons,personComparer); Console.WriteLine("排序后的结果:"); Person.ShowPersons(persons);
Person personToBeFind=new Person(); Console.WriteLine("输入ID"); personToBeFind.ID=int.Parse(Console.ReadLine()); Console.WriteLine("输入Age"); personToBeFind.Age=int .Parse(Console.ReadLine());
// BinarySearch 对半查找 int index=Array.BinarySearch(persons,personToBeFind,personComparer); if(index>=0) Console.WriteLine("待查找的元素是数组的第{0}个元素",index+1); else Console.WriteLine("对不起,没有所找的元素"); Console.ReadLine(); } }}
ICollection 接口 定义所有集合的大小、枚举数和同步方法,是 System.Collections 命名空间中类的基接口。IDictionary 和 IList 是基于 ICollection 接口的更专用的接口。IDictionary 实现是键/值对的集合,如 Hashtable 类。IList 实现是可被排序且可按照索引访问其成员的值的集合,如 ArrayList 类。
某些集合(如 Queue 类和 Stack 类)限制对其成员的访问,它们直接实现 ICollection 接口。
如果 IDictionary 接口和 IList 接口都不能满足所需集合的要求,则从 ICollection 接口派生新集合类以提高灵活性。在一个集合中进行顺序枚举时常见的任务int index;index = Array.IndexOf(authors,"Richard");if (index != -1){ Response.Write("<p>"+authors[index]+"is in the author list);}
Array和IList内置的Array类型执行IList接口 但仅实现该接口的 IndexOf Clear Contains方法以及一个属性item,如果想调用其他IList成员 就会产生NotSupportedException IList的其他成员定义为外部接口成员 必须通过IList接口才可以访问
例如void Page_Load(Object sender, EventArgs args ) {
String[] authors = new String[] {"Richard","Alex", "Dave","Rob","Brian","Karli"};
int index; index = Array.IndexOf(authors,"Richard"); if (index != -1) { outResult.InnerHtml = authors[index] + " is in the author list<br />"; }
IList list;
list = (IList) authors; if (list.Contains("Richard")) { index = list.IndexOf("Richard"); outResult.InnerHtml += list[index] + " is in the author list"; }
}
ArrayList类执行IList接口,它可以实现和使用所有的IList方法 ArrayList类可以隐式地把IList接口成员作为公用接口<script runat="server">
ArrayList movieList = new ArrayList();
void Page_Load(Object Sender, EventArgs Args) { if (IsPostBack == true) { movieList = (ArrayList) ViewState["movies"]; } else { movieList = new ArrayList(); movieList.Add("Pulp Fiction"); movieList.Add("Aliens"); movieList.Add("The Good, the Bad and the Ugly"); ViewState["movies"] = movieList; ShowList(); }}
void ShowList() { if (movieList.Count > 0) { foreach (String Movie in movieList) { outList.InnerHtml += Movie + "<br />"; } } else { outList.InnerHtml = "There are no movies in the list."; }}
// add an item to the listvoid OnAddMovie(Object Sender, EventArgs Args) { movieList.Add(MovieName.Text); ShowList();}
// delete an item from the listvoid OnDeleteMovie(Object Sender, EventArgs Args) { if (movieList.IndexOf(MovieName.Text) == -1) { status.InnerHtml = "Movie not found in list"; } else { movieList.Remove(MovieName.Text); } ShowList();}
// sort the listvoid OnSortList(Object Sender, EventArgs Args) { movieList.Sort(); ShowList();}
// class that implements the comparison logic for the sortclass MyComparer : IComparer{ public int Compare( object x, object y ) { IComparable ic; int compareResult; ic = (IComparable) x; compareResult = ic.CompareTo( y ); if ( compareResult != 0 ) compareResult = compareResult * -1; return compareResult; }}
// custom sort using MyComparervoid OnCustomSortList(Object Sender, EventArgs Args) { IComparer custom = new MyComparer(); movieList.Sort(custom); ShowList();}
</script>
特别提醒:在ArrayList 中添加项目时 内部数组的大小会根据需要自动扩展 默认大小是16,如果知道列表中项目的数目,就应该优化列表初始的容量否则 当列表尺寸增大时 多次所内存分配和项目复制操作就会占用比较的多的系统资源ArrayList list = new ArrayList()list.Capacity = 128;一旦列表填充了项目 就可以调用 TrimToSize()方法来释放未使用的存取空间
IDictionary 实现是键/值对的集合,如 Hashtable 类。Hashtable类 表示相关关键字和值的一个字段 显示为散列表 可以使用关键字值的散列有效的存储和检索值
例如void Page_Load(Object sender, EventArgs args ) {
Hashtable ourSession = new Hashtable(); ourSession["value1"] = "Wrox"; ourSession["value2"] = "Wiley"; String value; foreach (String key in ourSession.Keys) { outResult.InnerHtml += "Key:" + key + " Value:" + ourSession[key] + "<br />"; } outResult.InnerHtml += "<p />";
if (ourSession.ContainsKey("value1") == true) { outResult.InnerHtml += "The key 'value1' is in the Hashtable<br />"; } if (ourSession.ContainsValue("Wrox") == true) { outResult.InnerHtml += "The value 'Wrox' is in the Hashtable"; }}
Hashtable类执行IEnumerable 所以可以枚举所有被包含的关键字和项目 调用Hashtable的IEnumerable.GetEnumerator方法 会返回一个枚举对象该枚举对象可以使用值类型的Systme.Collecion.DictionaryEntry来显示被包含的项目foreach(DictionaryEntry entry in table){ Reponse.Write(entry.Key+entry.Value);}
Hashtable对象的公用GetEnumerator方法返回一个IDictionaryEnumerator接口,此枚举对象包含了IEnumerator所有的方法和属性 还有三个额外的属性用来显示当前项目的Key Value DictionaryEntry 在不使用foreach时 使用这些额外的属性返回自定义枚举可以减少类型转换 因为CLR必须坚持类型转换是否安全而类型转换又会导致性能开销
例如IDictionaryEnumerator e;e = table.GetEnumerator();while(e.MoveNext()){ Response.Write("<Br/>Key" + e.Key +"Value:"+e.Value);}
IDidtionary接口 该接口定义了一些属性和方法 可用来处理关键字和与之相关的值的未排序集合,在IDidtionary接口中 关键字和值都定义为System.Object了类型,此接口继承于ICollction
Case Sensitivity in Hashcode Generation
void Page_Load(Object sender, EventArgs args ) {
String name1, name2;
name1 = "Richard"; name2 = "RICHARD";
outResult1.InnerHtml = "Hash code for '" + name1 + "' is " + name1.GetHashCode(); outResult1.InnerHtml += "<br />Hash code for '" + name2 + "' is " + name2.GetHashCode();
IHashCodeProvider hcp; hcp = CaseInsensitiveHashCodeProvider.Default;
outResult2.InnerHtml = "Hash code for '" + name1 + "' is " + hcp.GetHashCode(name1); outResult2.InnerHtml += "<br />Hash code for '" + name2 + "' is " + hcp.GetHashCode(name2);
}
A Sorted View of an Existing Collection
void Page_Load(Object sender, EventArgs args ) {
Hashtable names = new Hashtable(); names.Add("RA", "Richard Anderson"); names.Add("DS", "David Sussman"); names.Add("RH", "Rob Howard"); names.Add("AH", "Alex Homer"); names.Add("KW", "Karli Watson"); names.Add("BF", "Brian Francis");
foreach (DictionaryEntry name in names) { outResult1.InnerHtml += "Key:" + name.Key + " - Value:" + name.Value + "<br />"; }
SortedList sortedNameList = new SortedList(names);
foreach (DictionaryEntry name in sortedNameList) { outResult2.InnerHtml += "Key:" + name.Key + " - Value:" + name.Value + "<br />"; }