Unity- IEnumerable:foreach中不能修改item的值

问题:通过foreach循环遍历IEnumerable是,修改其item值失败,如下图

原因探究:

1.IEnumerable接口内部实现如下:

  public interface IEnumerable<out T> : IEnumerable
  {
    /// <summary><para>Returns an enumerator that iterates through the collection.</para></summary>
    IEnumerator<T> GetEnumerator();
  }

2.IEnumerator内部实现如下

  public interface IEnumerator
  {
    /// <summary><para>Advances the enumerator to the next element of the collection.</para></summary>
    bool MoveNext();

    /// <summary><para>Gets the current element in the collection.</para></summary>
    object Current { get; }

    /// <summary><para>Sets the enumerator to its initial position, which is before the first element in the collection.</para></summary>
    void Reset();
  }

3.foreach遍历机制相当于通过Enumerator的MoveNext方法和Current属性进行遍历,上图代码等价于下图:


4.总结:IEnumerator的Current属性值定义就只有get没有set,所以其是只读的,不可修改

解决方案:将IEnumerable转成List,在List中Current会被重写并允许修改,如下图:

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.迭代器   首先我们要谈的就是迭代器,很多情况下我们都使用了迭代器,并不仅仅是因为协程,当我们使用foreac...
    joshuaAS阅读 2,885评论 1 4
  • 数据结构 一般将数据结构分为两大类: 线性数据结构和非线性数据结构。 线性数据结构有: 线性表、栈、队列、串、数组...
    沉麟阅读 924评论 0 0
  • 什么是IEnumerable? 什么是IEnumerable?IEnumerable及IEnumerable的泛型...
    aslbutton阅读 657评论 0 51
  • 关于这个话题,网络上讨论的很多,我也收集了一些资料,都不是很齐全,所以自己亲自测试,这里把结果分享给大家。 for...
    AndrewFan阅读 2,075评论 3 18
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,606评论 28 53