問題:通過foreach循環(huán)遍歷IEnumerable是,修改其item值失敗,如下圖

原因探究:
1.IEnumerable接口內(nèi)部實現(xiàn)如下:
public interface IEnumerable<out T> : IEnumerable
{
/// <summary><para>Returns an enumerator that iterates through the collection.</para></summary>
IEnumerator<T> GetEnumerator();
}
2.IEnumerator內(nèi)部實現(xiàn)如下
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轉(zhuǎn)成List,在List中Current會被重寫并允許修改,如下圖:
