我在 foreach 循环内有一个嵌套的 while 循环,我想在满足特定条件时无限期地推进枚举器。为此,我尝试将枚举器转换为 IEnumerator (如果它位于 foreach 循环中,则必须如此),然后在转换的对象上调用 MoveNext() ,但它给我一个错误,说我无法转换它。
无法通过引用转换、装箱转换、拆箱转换、包装转换或 null 类型转换将类型“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
,这可能会很好地帮助您做您需要做的事情。但是,为了显示手动移动枚举器,首先您必须have枚举器,这意味着将循环编写为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
}
}
根据您的评论:
如果 foreach 循环没有实现 IEnumerator 接口,它如何推进它?
在你的循环中,time
is a DateTime
。它不是需要实现接口或模式才能在循环中工作的对象。times
是一个序列DateTime
值,它是必须实现可枚举模式的值。这通常是通过实施IEnumerable<T>
and IEnumerable
接口,只需要T GetEnumerator()
and object GetEnumerator()
方法。这些方法返回一个实现的对象IEnumerator<T>
and IEnumerator
,它定义了一个bool MoveNext()
方法和一个T
or object Current
财产。但time
无法投射到IEnumerator
,因为它不是这样的事情,也不是times
顺序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)