1. Define collection class
The simplest way to define a collection class in C # is to use the abstract class collectionbase class found in the system. Collections Library as the basic class. This class provides a set of abstract methods that can be used to construct a cluster. The collectionbase class also provides a basic data structure-innerlist (an arraylist ). This structure can be used as the basis of its own class. This section describes how to use collectionbase to construct a collection class.
2. Implement collection class
All methods to make up for the Collection class include some types that interact with the basic data structure innerlist of the class. The method to be implemented in the first part of this section is the add, remove, count, and clear methods. Although other defined methods can make the class more useful, these methods are the absolute basic elements of the class. Count is most often implemented as an attribute, but here we prefer to use it as a method. Besides, because count is implemented in the basic class collectionbase, new keywords must be used to hide the Count found in collectionbase.
. Similarly, remove is similar.
3. The specific implementation code is as follows:
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. Call the following method to test the complex type:
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; } }