System.Collections深入探讨如何创建自定义的集合类

关键字:collection集合,ArrayList数组队列,Generic 泛型,List<T>列表,自定义集合类
正文:
    在System.Collections namespace下面,存在两个class ,分别为ArrayList和 List<T> ,都可以实现对象的数组队列。那么两者之间到底有什么区别呢?如何利用其创建自定义的集合类呢?
    
1. ArrayList
ArrayList对象主要的方法包括:
     1:Add()向数组中添加一个元素,
     2:Remove()删除数组中的一个元素
     3:RemoveAt(int i)删除数组中索引值为i的元素
     4:Reverse()反转数组的元素
     5:Sort()以从小到大的顺序排列数组的元素
     6:Clone()复制一个数组
其主要缺点是:当对非valueType的变量进行Add操作时,compiler会自动进行一个boxing操作。因此,不管任何类型的object,都可以Add至ArrayList中,这样就破坏了类型安全性(type security)
例如:
 using System.Collections
public class Program
{
ArrayList al=new ArrayList();
al.Add(1);
al.Add("12");
al.Add(2.3);
}
/*
这样的Add操作往往背后hide相应的boxing operation。 而且可以看出,这些插入的对象相互之间即使没有任何逻辑上的联系,也可以Add, compiler不会报措!
*/

2. List<>
        可通过索引访问的对象的强类型列表, LIst是一种泛型Generic。提供用于对列表进行搜索、排序和操作的方法。其作用应该和ArrayList差不多。
        但是,List<>是支持强类型的。也就是List<>在进行Add operation的时候,compiler会进行类型的检查。从而在compile阶段,就可以发现不安全的类型。
 using System.Collections
public class Program
{
List<int> _list=new List<int>;
al.Add(1);//ok
al.Add("12");//error!  did not pass type security check
al.Add(2.3);//error!
}

3. 如何构建自定义集合类型。
        当某个对象由另外若干个相同对象组成时,我们就可以定义该对象为集合类型,这样就可以对该对象内的组成对象进行枚举操作(IEnumerable)。
        题外话:IEnumerable和IEnumerator什么区别?
        答:结构如下:
            public interface IEnumerabe
            {
                IEnumerator GetEnumerator();
            }
            public interface IEnumerator
            {
                object Current();
             bool MoveNext();
                 ......
            }
            实际上,ArrayList和List<>都已经实现了IEnumerator的接口,因此一般情况下我们不必要自己实现这些interface。
        因此,如果要创建自定义的集合类,我们必须继承自IEnumerator接口,并且实现IEnumerator的GetEnumerate方法。当然,我们不可能亲自去implement IEnumerator如此多的方法,我们都会借助于ArrayList或者List<>的GetEnumerate方法。
示例如下:
学生类
public class Student
{
    public Student(string name)
    {
        _name=name;
    }
    public void ShowInformation()
    {
        Console.WriteLine(_name);
    }
    private string _name;
}
学生集合类
 public class StudentCollections:IEnumerable
{
    private List<Student> stuColl=new List<Student>;
    public void Add(Student stu)
    {
        stuColl.Add(stu);
    }    
     public IEnumerator GetEnumerator()
    {
        stuColl.GetEnumerator();
    }
 }


客户端调用:
public class Program
{
public static void Main()
{
StudentCollections stucoll=new StudentCollections();
stucoll.Add(new Student("herengang"));
stuconl.Add(new Student("hrg"));
foreach(Student stu in stucoll)  //集合类的枚举内部对象的操作
    stu.Show();
}
}
完成!这样就实现了一个自定义的集合类。以上集合类我们采用了List<>来实现。实际上我们也可以采用ArrayList。当然,Generic是在C# 2.0才推出的 :)

原文地址:https://www.cnblogs.com/Winston/p/1210143.html