转: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.具体实现代码如下
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Collections;
- namespace ConsoleApplication1
- {
- public class MyCollection : CollectionBase
- {
- public void Add(Object Item)
- {
- InnerList.Add(Item);
- }
- public void Remove(Object Item)
- {
- InnerList.Remove(Item);
- }
- public new int Count()
- {
- return InnerList.Count;
- }
- public new void Clear()
- {
- InnerList.Clear();
- }
- }
- }
4.调用方法如下,使用复杂类型测试:
- class Program
- {
- static void Main(string[] args)
- {
- MyCollection stus = new MyCollection();
- Student s1 = new Student(1, "aaa");
- Student s2 = new Student(2, "bbb");
- Student s3 = new Student(3, "ccc");
- stus.Add(s1);
- stus.Add(s2);
- stus.Add(s3);
- foreach (Student c in stus)
- {
- Console.WriteLine(c.Name);
- }
- Console.WriteLine(stus.Count());
- Console.ReadLine();
- }
- }
- public class Student
- {
- private int id;
- public int Id
- {
- get { return id; }
- }
- private string name;
- public string Name
- {
- get { return name; }
- }
- public Student(int id,string name)
- {
- this.id = id;
- this.name = name;
- }
- }
浙公网安备 33010602011771号