构建自定义集合-实现强类型安全
说明:1.创建一个类;2.创建该类的集合。研究意义大于实际意义
public class Person { //说明:在.net2.0泛型以前,程序员会尝试通过手动构建强类型集合来实现类型安全: public int Age; public String FirstName; public string LastName; public Person() { } public Person(string firstname, string LastName,int age) { this.FirstName = firstname; this.LastName = LastName; this.Age=age; } public override string ToString() { return string.Format("Name:{0} {1},Age:{2}",FirstName,LastName,Age); } }
2创建集合类
public class PeopleCollection:IEnumerable { private ArrayList arPeople = new ArrayList(); public PeopleCollection() { } //通过索引访问 public Person GetPerson(int index) { return (Person)arPeople[index]; } //增加person,保证只能增加Person类型 public void AddPerson(Person p) { arPeople.Add(p); } //清空集合 public void ClearPeople() { arPeople.Clear(); } //实现IEnumber接口,支持foreach枚举 public IEnumerator GetEnumerator() { return arPeople.GetEnumerator(); } }
3.调用
static void Main(string[] args) { PeopleCollection collection = new PeopleCollection(); collection.AddPerson(new Person { Age=10, FirstName="first",LastName="Last"}); collection.AddPerson(new Person { Age = 11, FirstName = "first1", LastName = "Last1" }); foreach (Person p in collection) { Console.WriteLine(p.ToString()); //这个地方我们重写了Tostring方法 } Console.ReadKey(); //虽然字定义集合可以保证类型安全,但是如果使用这种方法,我们必须每一个 //希望包含的类型创建这样一个自定义集合,可以思考下泛型的优点。 }

浙公网安备 33010602011771号