美文网首页
Unity- IEnumerable:foreach中不能修改i

Unity- IEnumerable:foreach中不能修改i

作者: CZKGO | 来源:发表于2021-05-21 11:26 被阅读0次

问题:通过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会被重写并允许修改,如下图:

相关文章

网友评论

      本文标题:Unity- IEnumerable:foreach中不能修改i

      本文链接:https://www.haomeiwen.com/subject/rrzijltx.html