zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    ES6初识-(冲突)数据结构
    ES6初识-Proxy和Reflect
    ES6初识- Class
    实时显示从file输入框中打开的图片C:fakepath路径问题
    php跨域访问
    移动端web开发技巧
    phpqrcode生成带logo的二维码图片
    iwebshop 自动给css js链接加版本信息
    微信统一支付接口返回“签名错误”的可能原因
    php smtp发送邮件功能
  • 原文地址:https://www.cnblogs.com/quietwalk/p/2180153.html
Copyright © 2011-2022 走看看