【发布时间】:2011-03-03 17:16:50
【问题描述】:
如果我自己实现IEnumerator 接口,那么我可以(在foreach 语句中)在albumsList 中添加或删除项目而不会产生异常。但是如果foreach 语句使用@987654325 @ 由albumsList 提供,然后尝试从albumsList 添加/删除(在foreach 中)项目将导致异常:
class Program
{
static void Main(string[] args)
{
string[] rockAlbums = { "rock", "roll", "rain dogs" };
ArrayList albumsList = new ArrayList(rockAlbums);
AlbumsCollection ac = new AlbumsCollection(albumsList);
foreach (string item in ac)
{
Console.WriteLine(item);
albumsList.Remove(item); //works
}
foreach (string item in albumsList)
{
albumsList.Remove(item); //exception
}
}
class MyEnumerator : IEnumerator
{
ArrayList table;
int _current = -1;
public Object Current
{
get
{
return table[_current];
}
}
public bool MoveNext()
{
if (_current + 1 < table.Count)
{
_current++;
return true;
}
else
return false;
}
public void Reset()
{
_current = -1;
}
public MyEnumerator(ArrayList albums)
{
this.table = albums;
}
}
class AlbumsCollection : IEnumerable
{
public ArrayList albums;
public IEnumerator GetEnumerator()
{
return new MyEnumerator(this.albums);
}
public AlbumsCollection(ArrayList albums)
{
this.albums = albums;
}
}
}
a) 我假设抛出异常的代码(使用 A 提供的 A 提供的 IEnumerator 时)位于 A 内?
b) 如果我希望能够从集合中添加/删除项目(foreach 正在对其进行迭代),我是否总是需要提供我自己的 IEnumerator 接口实现,或者可以设置 AlbumsList允许添加/删除项目?
谢谢
【问题讨论】:
标签: c# ienumerable