自己实现的集合类,如何防止 foreach中途退出后 当前的location位置不对?

progame 2003-04-25 02:55:56
因为线程被终止,所以foreach并未执行完

结果下次执行前我只能使用CMyClass.Reset()复位才行

有别的方法么?
...全文
46 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
progame 2003-04-25
  • 打赏
  • 举报
回复
o
timmy3310 2003-04-25
  • 打赏
  • 举报
回复
比如:

internal class SomeEnumerator
{
private YourClass _data;
public SomeEunmerator( YourClass obj )
{
_data = obj;
}

public object Current
{
// 得到集合当前的元素
get
{
CFileItem item = (CFileItem)_data.m_Files[this.m_Location - 1];

return (object)item;
}
}
public void Reset()
{
_data.m_Location = 0;
}
public bool MoveNext()
{
_data.m_Location++;
if (_data.m_Location > _data.m_Files.Count)
{
_data.m_Location = 0;
return false;
}
else
return true;
}

}
timmy3310 2003-04-25
  • 打赏
  • 举报
回复
你可以写一个内部类来帮你实现IEnumerator,而在:

public IEnumerator GetEnumerator()
{
return new SomeEnumerator(this); //每次foreach都返回一个新实例
}

然后在SomeEnumerator实现IEnumerator的方法,也就是MoveNext、Reset等,在GetEnumerator里面每次都返回一个实例的话,就不会受到一个foreach没有正常执行完,内部的Localtion会影响下一次了
progame 2003-04-25
  • 打赏
  • 举报
回复
#region 集合实现
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}

public object Current
{
// 得到集合当前的元素
get
{
CFileItem item = (CFileItem)this.m_Files[this.m_Location - 1];

return (object)item;
}
}
public void Reset()
{
this.m_Location = 0;
}
public bool MoveNext()
{
this.m_Location++;

if (this.m_Location > this.m_Files.Count)
{
this.m_Location = 0;
return false;
}
else
return true;
}


#endregion
timmy3310 2003-04-25
  • 打赏
  • 举报
回复
把你的类代码贴出来

111,093

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧