• C#中Collection,List和ArrayList的区别(转)


    http://blog.csdn.net/cronzb/article/details/6429241

    在C# .net 2.0 库中,集合类就是在System、System.Collections、System.Collections.Generic和 System.Collections.ObjectModel命名空间下的类,包括Collection, KeyedCollection, ReadOnlyCollection, List, Array,Stack, Queue和ArrayList。

    下面是Collection<T>, List<T>和ArrayList三个类的区别

    1. List是用来在高性能环境下的类,Collection是为了扩展

    使用Collection,开发人员可以重写ClearItems, InsertItem, RemoveItem 和SetItem, 因为它们是protected virtual类型的,而List<T>却没有这些扩展。

    2. 实现的接口不一样

    Collection<T>实现IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollectionIEnumerable

    List<T>实现IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollectionIEnumerable

    ArrayList实现IList, ICollection, IEnumerable, ICloneable

    IList<T>,ICollection<T>, IEnumerable<T>和IList, ICollection, IEnumerable是完全不同的,前者用于范型,

    1. public interface IList<T> : ICollection<T>, IEnumerable<T>IEnumerable  
    2. {  
    3.     T Item;  
    4.     abstract int IndexOf(T item);  
    5.     abstract void Insert(int index, T item);  
    6.     abstract void RemoveAt(int index);  
    7. }  
    8. public interface IList : ICollectionIEnumerable  
    9. {  
    10.     bool IsFixedSize;  
    11.     bool IsReadOnly;  
    12.     object Item;  
    13.     abstract int Add(object value);  
    14.     abstract void Clear();  
    15.     abstract bool Contains(object value);  
    16.     abstract int IndexOf(object value);  
    17.     abstract void Insert(int index, object value);  
    18.     abstract void Remove(object value);  
    19.     abstract void RemoveAt(int index);  
    20. }  
     

    另一方面,Collection<T>和List<T>也实现了IList, ICollectionIEnumerable,说明这两个类比ArrayList提供了更多的方法。

    3. 范型与非范型的区别

    ArrayList是非范型类,如此,这个集合可以包含不同类型成员,我们可以看到,Add方法是Add(Object obj),所以这是一个对象杂陈的类。使用这个类进行操作时,IndexOf,Remove等都要使用类的Equals和HashCode,所以如果是自 己实现的类,一定要判断是否同一类型。

    比如这个类是 TestType

    1. public override bool Equals(Object obj)  
    2. {  
    3.     TestType tType = obj as TestType;  
    4.     if (tType == null)  
    5.     {  
    6.         return false;  
    7.     }  
    8.     //其它业务代码  
    9.     ...  
    10. }  
     

    总结:

    如果有扩展要求,可以考虑使用Collection<T>,如果有性能要求,考虑用List<T>,如果想存放不同类型的对象,使用ArrayList。

    本文参考了.net 2.0类库和http://blogs.msdn.com/b/codeanalysis/archive/2006/04/27/585476.aspx

  • 相关阅读:
    解决Android中无法搜索联系人的问题
    在InstallShield中发布单一的Setup.exe文件
    log4net使用简介
    h264格式的flv和mkv无损转换成mp4的方法
    使用boost.filesystem进行文件操作
    Tcp连接的七次握手浅析
    Android ICS系统是支持通过互联网时间同步的
    解决从其它搜索引擎不能直接访问百度页面的问题
    _ttoi 代替atoi
    windows 下VLC播放器应用之二LIBVLC API解析
  • 原文地址:https://www.cnblogs.com/quietwalk/p/2180153.html
Copyright © 2020-2023  润新知