既然你提到IEnumerable[<T>]
(不是IList[<T>]
等),我们不能依赖计数等:所以我很想展开foreach
:
using(var iter = source.GetEnumerator()) {
if(iter.MoveNext()) {
T last = iter.Current;
while(iter.MoveNext()) {
// here, "last" is a non-final value; do something with "last"
last = iter.Current;
}
// here, "last" is the FINAL one; do something else with "last"
}
}
请注意,上述内容在技术上仅适用于IEnuemerable<T>
; 对于非泛型,您需要:
var iter = source.GetEnumerator();
using(iter as IDisposable) {
if(iter.MoveNext()) {
SomeType last = (SomeType) iter.Current;
while(iter.MoveNext()) {
// here, "last" is a non-final value; do something with "last"
last = (SomeType) iter.Current;
}
// here, "last" is the FINAL one; do something else with "last"
}
}