【发布时间】:2012-03-04 11:45:16
【问题描述】:
我在 foreach 循环中有一个嵌套的 while 循环,我想在满足某个条件时无限期地推进枚举数。为此,我尝试将枚举器强制转换为 IEnumerator (如果它在 foreach 循环中则必须如此),然后在强制转换的对象上调用 MoveNext() 但它给了我一个错误,说我无法转换它。
无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换将类型“System.DateTime”转换为 System.Collections.Generic.IEnumerator。
foreach (DateTime time in times)
{
while (condition)
{
// perform action
// move to next item
(time as IEnumerator<DateTime>).MoveNext(); // will not let me do this
}
// code to execute after while condition is met
}
在 foreach 循环中手动增加 IEnumerator 的最佳方法是什么?
编辑: 编辑显示在 while 循环之后有代码,一旦满足条件,我想执行,这就是为什么我想在 while 内手动递增然后打破它,而不是 continue 让我回到顶部。如果这不可能,我相信最好的办法是重新设计我的做法。
【问题讨论】:
-
除了答案之外,您可能还缺少一件事:
time是DateTime,它没有实现IEnumerator -
如果foreach循环没有实现IEnumerator接口,它怎么能推进它?
-
看看你的代码。
foreach (DateTime time in times)。times是被枚举的对象。 -
枚举器永远不是您的对象之一。否则你不能有多个线程迭代同一个对象
标签: c# loops foreach ienumerable ienumerator