问题:通过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,所以其是只读的,不可修改