c# – 手动增加foreach循环内的枚举器
我在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 } 在foreach循环中手动增加IEnumerator的最佳方法是什么? 编辑: 解决方法
许多其他答案建议使用continue,这可能很好地帮助您做您需要做的事情.但是,为了显示手动移动枚举器,首先必须使用枚举器,这意味着将循环写入一段时间.
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 } } 从你的评论:
在循环中,时间是DateTime.不需要在循环中实现接口或模式的对象. times是一系列DateTime值,它是必须实现可枚举模式的值.这通常通过实现IEnumerable< T>来实现.和IEnumerable接口,它们只需要T GetEnumerator()和对象GetEnumerator()方法.该方法返回实现IEnumerator< T>的对象.和IEnumerator,它们定义了一个bool MoveNext()方法和一个T或对象Current属性.但是时间不能转换为IEnumerator,因为它不是这样的,也不是时间序列. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |