問題:通過foreach循環(huán)遍歷IEnumerable是赡若,修改其item值失敗谤碳,如下圖
原因探究:
1.IEnumerable接口內部實現(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內部實現(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酬凳,所以其是只讀的,不可修改