zoukankan      html  css  js  c++  java
  • 如何选择使用IEnumerable, ICollection, IList

    IEnumerable, ICollection, IList,每种接口只适合某些特定场景,如何区别使用呢?

    IEnumerable接口,只提供了一个获取迭代器的方法,这也是为什么可以使用foreach遍历实现了IEnumerable接口集合的原因。

    
    
    public interface IEnumerable
    
    {
    
        IEnumerator GetEnumerator();
    
    }

    ICollection实现了IEnumerable接口,因此,除了拥有IEnumerable接口的能力,还包括其它能力。

    
    
    public interface ICollection : IEnumerable
    
    {
    
        int Count{get;}
    
        bool IsSynchronized{get;}
    
        Object SyncRoot{get;}
    
    
    
        IEnumerator GetEnumerator();
    
        void CopyTo(Array array, int index);
    
    }
    
    
    
    

    IList同时实现了ICollection和IEnumerable接口,在2个接口的基础上,可以添加、移除或清空集合,还提供了根据索引访问集合元素。

    
    
    public interface IList : ICollection, IEnumerable
    
    {
    
        bool IsFixedSize{get;}
    
        bool IsReadOnly{get;}
    
        Object this[int index] {get;set;}
    
    
    
        int Add(Object value);
    
        void Clear();
    
        bool Contains(Object value);
    
        int IndexOf(Object value);
    
        void Insert(int index, Object value);
    
        void Remove(Object value);
    
        void RemoveAt(int index);
    
    }
    
    
    
    
    
    

    总结:

    ● 如果只想遍历集合,使用IEnumerable, IEnumerable<T>
    ● 如果想遍历、修改集合,以及需要延迟加载的导航属性,使用ICollection, ICollection<T>
    ● 如果想遍历、修改、添加、清空、使用索引,使用IList, IList<T>

  • 相关阅读:
    保持简单----纪念丹尼斯•里奇(Dennis Ritchie)
    转:有关retina和HiDPI那点事
    Powershell 学习
    Windows与Linux共享文件夹互相访问
    你知道C语言为什么会有“_”(下划线)吗?
    百度公共DNS
    AXIS2的一些认识
    待整理
    java复习汇总之面试篇
    落网歌曲图片下载
  • 原文地址:https://www.cnblogs.com/hedianzhan/p/8733506.html
Copyright © 2011-2022 走看看