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;
        }
    }


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值