日期:2012-08-08  浏览次数:20409 次

Creating Collection Classes in C#

Introduction
Collection classes are used frequently in .NET. For example, classes like ArrayList, NamevalueCollection, HashTable are collection classes. One peculiar thing of collection classes is that they can be used in foreach(...) loop in C#. VB.NET has similar construct For...Each. Your custom classes can also be iterated in this way if you implement certain interfaces. In this article we will see how to code collection classes using C#.
Sample Class
For our example we will assume that we need some data structure in whch we will store list of book titles. We should be able to add, remove and iterate through the set of book titles. We will create a collection class called Books that will stire these titles. Before going in to the details of creating collection class let us see the Books class in its most basic form.
namespace CollectionClass
{
class Books
{
        private ArrayList m_booktitles;
        public Books()
        {
               m_booktitles=new ArrayList();
        }

        public void Add(string booktitle)
        {
               m_booktitles.Add(booktitle);
        }

        public void Remove(string booktitle)
        {
               m_booktitles.Remove(booktitle);
        }
}
}
You will notice that we have provided easy way to add and remove items to the books class via ArrayList. However, we can not iterate the class using foreach construct. In order to achieve this we have to :
  • Implement System.Collections.IEnumerable interface in Books class
  • Create a class that implements System.Collections.IEnumerator interface

IEnumerable Interface
IEnumerable interface has only one method GetEnumerator() that returns a class that implements IEnumerator interface. Following code shows Books class after implementing IEnumerable interface.
class Books:IEnumerable
{
        public ArrayList m_booktitles;

        public Books()
        {
               m_booktitles=new ArrayList();
        }

        public void Add(string booktitle)
        {
               m_booktitles.Add(booktitle);
        }

        public void Remove(string booktitle)
        {
               m_booktitles.Remove(booktitle);
        }

        public IEnumerator GetEnumerator()
        {
               return new BooksEnumerator(this);
  &nb