Des*_*tar 6 c# ienumerable ienumerator foreach loops
我在foreach循环中有一个嵌套的while循环,我希望在满足某个条件时无限期地推进枚举器.为此,我尝试将枚举器强制转换为IEnumerator <T>(如果它在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
}
Run Code Online (Sandbox Code Playgroud)
在foreach循环中手动增加IEnumerator的最佳方法是什么?
编辑:编辑显示有一个条件满足后我想要执行的while循环之后的代码这就是为什么我想在内部手动递增然后突破它而不是继续这会让我回到顶部.如果这是不可能的,我相信最好的事情是重新设计我是如何做到的.
Ant*_*ram 12
许多其他答案建议使用continue
,这可能很好地帮助您做您需要做的事情.但是,为了显示手动移动枚举器,首先必须有枚举器,这意味着将循环编写为while
.
using (var enumerator = times.GetEnumerator())
{
DateTime time;
while (enumerator.MoveNext())
{
time = enumerator.Current;
// pre-condition code
while (condition)
{
if (enumerator.MoveNext())
{
time = enumerator.Current;
// condition code
}
else
{
condition = false;
}
}
// post-condition code
}
}
Run Code Online (Sandbox Code Playgroud)
从你的评论:
如果没有实现IEnumerator接口,foreach循环如何推进呢?
在你的循环中,time
是一个DateTime
.不需要在循环中实现接口或模式的对象.times
是一系列DateTime
值,它是必须实现可枚举模式的值.这通常通过实现简单需要和方法的IEnumerable<T>
和IEnumerable
接口来实现.该方法返回执行的对象和,它定义一个方法和一个或属性.但不能投,因为它不是这样的事情,也不是序列.T GetEnumerator()
object GetEnumerator()
IEnumerator<T>
IEnumerator
bool MoveNext()
T
object Current
time
IEnumerator
times
您无法从for循环内部修改枚举器.该语言不允许这样做.您需要使用continue语句才能进入循环的下一次迭代.
但是,我不相信你的循环甚至需要继续.继续阅读.
在代码的上下文中,您需要将while转换为if以使continue继续引用foreach块.
foreach (DateTime time in times)
{
if (condition)
{
// perform action
continue;
}
// code to execute if condition is not met
}
Run Code Online (Sandbox Code Playgroud)
但是这样编写很明显,以下等效变体仍然更简单
foreach (DateTime time in times)
{
if (condition)
{
// perform action
}
else
{
// code to execute if condition is not met
}
}
Run Code Online (Sandbox Code Playgroud)
这相当于您的伪代码,因为对于条件为false的每个项,将执行在满足条件之后执行的标记代码的部分.
我在所有这些中的假设是对列表中的每个项目评估条件.