C#学习小记(1) - 集合接口ICollection,IEnumerable,IEnumerator等的关系

这是博主看书的暂时的小记,未来有时间会整理成学习资料,目前仅供看着乐

今天看书看到泛型,泛型中用集合接口做了例子,就想顺便理一下集合的各种接口的意思

咱先假定已经知道什么是接口了,啊
注:以下大部分内容,只要在后面加一个< T > ,就可以泛型啦
C#中实现集合有很多办法,比如说数组,比如说ArrayList,比如说List

话说相比之下ArrayList和List比起来似乎一无是处,回头做个比较。

那么这么多办法还有一个就是自建一个集合类,是的,就和List一样,高大上。

那你想做这么个类,为了融入环境,人家List能做的,你也得能做,那就得实现他的接口了

那List的接口有……

[SerializableAttribute]
public class List<T> : IList<T>, ICollection<T>, 
    IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, 
    IEnumerable

……喂这和说好的不一样啊

没事慢慢来

IEnumerable接口包含一个GetEnumerator()方法

GetEnumerator()返回一个IEnumerator,不懂的话,返回一个实现了IEnumerator接口的类,没错,就是迭代器

那这个类是什么

啊,你得自己写(掩面)

当然得符合规范,这个类得实现了IEnumerator接口

IEnumerator要求类实现了类似于c++中前向迭代器的功能,对,前向迭代器,他只能movenext或者reset。不过这对于foreach来说也足够了

那到你手里要怎么实现呢,看官方例子

// Defines the enumerator for the Boxes collection.
// (Some prefer this class nested in the collection class.)
public class BoxEnumerator : IEnumerator<Box>
{
    private BoxCollection _collection;
    private int curIndex;
    private Box curBox;


    public BoxEnumerator(BoxCollection collection)
    {
        _collection = collection;
        curIndex = -1;
        curBox = default(Box);

    }

    public bool MoveNext()
    {
        //Avoids going beyond the end of the collection.
        if (++curIndex >= _collection.Count)
        {
            return false;
        }
        else
        {
            // Set current box to next item in collection.
            curBox = _collection[curIndex];
        }
        return true;
    }

    public void Reset() { curIndex = -1; }

    void IDisposable.Dispose() { }

    public Box Current
    {
        get { return curBox; }
    }


    object IEnumerator.Current
    {
        get { return Current; }
    }

}

略看一下,可以先总结出来几点
1.Current属性返回当前指着的东西(没错,解引用)
2.MoveNext()让下一次调用Current的时候指着下一个东西
3.Reset()让一切从头开始
可以看到,在最初始的状态,直接用Current的话,索引在-1。
这意味着想要遍历,必须先MoveNext再Current
同时,MoveNext在移动到的下个位置可用时返回true

对了,我们可以在这里推测出foreach的工作原理:
while (a.MoveNext())
dosomething(a.Current)
当然这都是题外话。

对了还有一个IDisposable接口,这是非泛型版本没有的,不过暂时不用管

这就是IEnumerable和IEnumerator,总结一下就是
实现了IEnumerable的类,可以用foreach对其迭代
然而为了实现IEnumerable,你还得自建一个实现了IEnumerator的类作为迭代器。

现在来讲ICollection。它是对IEnumerable的扩展,增加了Add,Clear,Contain等方法。简单的来说就是功能更强。

IList则是ICollection的增强,则实现了按索引修改、查找等神奇功能,对,一层层加强下来功能基本上就是c++里头的vector了(只是说功能,具体效率、空间等和实现方法有关)

ICollection的增强还有个分支,就是IDictionary,要求实现键值对的查找,实现了他的就是Dictionary,这是啥,对,就是STL_map。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值