首页 > 学院 > 开发设计 > 正文

foreach的一点理解

2019-11-17 02:22:18
字体:
来源:转载
供稿:网友

foreach的一点理解

首先什么样的数据才能实现foreach

1 实现IEnumerable这个接口

2 有GetEnumerable()这个方法

然后为啥实现这个接口或者有这个方法就可以实现foreach遍历

首先我先用反编译器看看里面到底是怎么实现的

然后我看了下 MoveNext的源码

public bool MoveNext(){    if (this.version != this.list._version)    {        throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));    }    if (this.index < this.endIndex)    {        this.currentElement = this.list[++this.index];        return true;    }    this.index = this.endIndex + 1;    return false;}

  和Current的源码

public object Current{    get    {        if (this.index < this.startIndex)        {            throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted"));        }        if (this.index > this.endIndex)        {            throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumEnded"));        }        return this.currentElement;    }}

  MoveNext里面基本就是索引+1 然后用索引(index)来确定currentElement

而Current里就是返回currentElement

这么说来 就是MoveNext来推动索引 从而遍历

foreach(var item in list)

现在我们再来讲讲foreach的全过程

首先复制需要索引的集合(list) 然后指针指向集合中第一位的前一个地址

然后开始执行 in 就是MoveNext执行的时候 推动指针 然后通过Current获得值 赋值给item

然后一直执行in 到item的操作 直到遍历完成


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表