实现代码原理如下: 1、继承一个CollectionBase抽象类,该类又继承IList, ICollection, IEnumerable接口。而该抽象类提供一套的抽象方法并且提供数据结构InnerList(ArrayList)来定制自己的集合类。后续文章会介绍一下ArrayList这个数据结构。 2、实现代码如下: using System;using System.Collections.Generic;using System.Collections;using System.Text; namespace DataStructureConsoleApplication{ class CollectionProgram:CollectionBase { //implementing the Add Method using the ArrayList public void Add(object item) { InnerList.Add(item); } //implementing the Remove Method using the ArrayList public void Remove(object item) { InnerList.Remove(item); } //implementing the Insert Method using the ArrayList public void Insert(int index,object item) { InnerList.Insert(index, item); } //implementing the Contains Method using the ArrayList public bool Contains(object item) { return InnerList.Contains(item); } //implementing the IndexOf Method using the ArrayList public int IndexOf(object item) { return InnerList.IndexOf(item); } //implementing the RemoveAt Method using the ArrayList public void RemoveAt(int index) { InnerList.RemoveAt(index); } //hide the method public new void Clear() { InnerList.Clear(); } //hide the property public new int count { get { return InnerList.Count; } } } class CollectionProgram1 { static void Main(string[] args) { CollectionProgram cps = new CollectionProgram(); cps.Add("goal"); cps.Add("bell"); cps.Add("love"); cps.Add("city"); cps.Add("Zhaoqing"); foreach (object cp in cps) { Console.WriteLine(cp); } Console.WriteLine("Number of cps:"+cps.count); cps.Remove("city"); Console.WriteLine("Number of cps:" + cps.count); cps.Insert(3,"city"); Console.WriteLine("Number of cps:" + cps.count); Console.WriteLine("Index of Number:" + cps.IndexOf("love")); cps.RemoveAt(2); Console.WriteLine("Index of Number:" + cps.IndexOf("love")); Console.WriteLine("Number of cps:" + cps.count); if (cps.Contains("Zhaoqing")) { Console.WriteLine("Right!"); } else { Console.WriteLine("Wrong!"); } cps.Clear(); Console.WriteLine("Number of cps:" + cps.count); } }} 运行结果: goal bell love city Zhaoqing Number of cps:5 Number of cps:4 Number of cps:5 Number of cps:2 Number of cps:-1 Number of cps:4 Right! Number of cps:0 希望大家来拍砖哦!:)

评论