using System;using System.Collections; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Person scott = new Person("Scott", "Hanselman"); Person bill = new Person("Bill", "Evjen"); Person srini = new Person("Srinivasa", "Sivakumar"); //ArrayList 包含着Person对象,实际还包括Object对象,也就是Arraylist还包括其他类对象 //固,下面要进行强制转换系统才知道他是什么类型 ArrayList people = new ArrayList(); people.Add(scott); people.Add(bill); people.Add(srini); Response.Write("<font color=blue>We used foreach.</font><BR/>"); foreach (Person p in people) { Response.Write(p.FullName + "<BR/>"); } Response.Write("<font color=red>Sort...</font><BR/>"); people.Sort(); Response.Write("<font color=blue>We used foreach.</font><BR/>"); foreach (Person p in people) { Response.Write(p.FullName + "<BR/>"); } //在数组people中索引 Person scott2 = new Person("Scott", "Hanselman"); int indexOfScott2 = people.IndexOf(scott2); Response.Write("<font color=red>indexof " + indexOfScott2 + "</font><BR/>"); //对已排序的搜索 int indexOfEquivalentScott = people.BinarySearch(scott2); Response.Write("<font color=red>BinarySearch " + indexOfEquivalentScott + "</font><BR/>"); Response.Write("<font color=blue>We used a for loop.</font><BR/>"); for (int i = 0; i < people.Count; i++) { //将Arraylist对象people对象进行强制转换成Peoson Response.Write(((Person)people[i]).FullName + "<BR/>"); } } } public class Person : IComparable{ string FirstName; string LastName; public Person(string first, string last) { FirstName = first; LastName = last; } public string FullName { get { return FirstName + " " + LastName; } } int IComparable.CompareTo(object obj) { //as 表示 后面接的是要转化成的 type, 比方说 //int i = 18; //object j = i as object; //这样i就被从int类型隐含转换成一个object类型 // 也可以写成 object j = (object)i; //将object类型转化为类类型 Person p2 = obj as Person; if (p2 == null) throw new ArgumentException("Object is not a Person!"); int lastNameResult = this.LastName.CompareTo(p2.LastName); if (lastNameResult == 0) { int firstNameResult = this.FirstName.CompareTo(p2.FirstName); return firstNameResult; } else { return lastNameResult; } } }

评论