转:C#数据结构和算法学习系列一----打造自己的Collection类

 1.定义Collection 类
在C#语言中定义一个Collection 类最简单的方法就是把在System.Collections 库中已找到的抽象类CollectionBase 类作为基础类。此类提供了一套可以实现构造自身群集的抽象方法集合。CollectionBase 类还提供了一种基础的数据结构——InnerList(一个ArrayList)。此结构可以用作自身类的基础。本章节会看到如何使用 CollectionBase 来构造Collection类。
2. 实现Collection 类
弥补Collection 类的全部方法包括一些与类的基础数据结构InnerList 相交互的类型。本节第一部分要实现的方法是Add 方法、Remove 方法、Count 方法和Clear 方法。尽管定义的其他方法可以使类更有用,但是上述这些方法是类的绝对基本要素。Count 最常作为属性来实现,但是这里更喜欢把它用作方法。而且,由于是在基础类CollectionBase 中实现Count, 所以必须用新的关键词来隐藏在CollectionBase 中找到的Count 的定义。同理,Remove类似。

3.具体实现代码如下

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Collections;  
  5.   
  6. namespace ConsoleApplication1  
  7. {  
  8.     public class MyCollection : CollectionBase  
  9.     {  
  10.         public void Add(Object Item)  
  11.         {  
  12.             InnerList.Add(Item);  
  13.         }  
  14.         public void Remove(Object Item)  
  15.         {  
  16.             InnerList.Remove(Item);  
  17.         }  
  18.         public new int Count()  
  19.         {  
  20.             return InnerList.Count;  
  21.         }  
  22.         public new void Clear()  
  23.         {  
  24.             InnerList.Clear();  
  25.         }  
  26.     }  
  27. }  


4.调用方法如下,使用复杂类型测试: 

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         MyCollection stus = new MyCollection();  
  6.         Student s1 = new Student(1, "aaa");  
  7.         Student s2 = new Student(2, "bbb");  
  8.         Student s3 = new Student(3, "ccc");  
  9.         stus.Add(s1);  
  10.         stus.Add(s2);  
  11.         stus.Add(s3);  
  12.         foreach (Student c in stus)  
  13.         {  
  14.             Console.WriteLine(c.Name);  
  15.         }  
  16.         Console.WriteLine(stus.Count());  
  17.         Console.ReadLine();  
  18.     }  
  19. }  
  20. public class Student  
  21. {  
  22.     private int id;  
  23.   
  24.     public int Id  
  25.     {  
  26.         get { return id; }  
  27.     }  
  28.     private string name;  
  29.   
  30.     public string Name  
  31.     {  
  32.         get { return name; }  
  33.     }  
  34.     public Student(int id,string name)  
  35.     {  
  36.         this.id = id;  
  37.         this.name = name;  
  38.     }  

posted @ 2011-11-07 15:52  追_bk  阅读(222)  评论(0编辑  收藏  举报