sq3*_*33G 4 c# try-catch yield-return
我需要在我作为迭代器(使用yield)实现的方法中做一些繁重的、有点脆弱的逻辑:
public IEnumerable<Things> GetMoreThings() {
while (goodStuffHappens()) {
Things moreThingsIWant = TemptFateAgain();
if (moreThingsIWant.Any())
yield return moreThingsIWant;
}
}
Run Code Online (Sandbox Code Playgroud)
在调用方法中,我需要将调用包装GetMoreThings在try/catch和yield return结果中:
try {
foreach (Things thing in Helpful.GetMoreThings())
yield return thing;
}
catch (Exception e) {
//crash, burn
}
Run Code Online (Sandbox Code Playgroud)
发起人会立即意识到这是不可能的 -在try/catch块(只有try/ finally)内没有诸如 yield 之类的东西。
有什么建议吗?
这里的两个答案都是正确的。这个没有内置快捷方式,您需要在一个while而不是for循环中梳理迭代器,以便在调用Enumerator.MoveNext()和使用Enumerator.Current.
IEnumerator<Things> iterator = Helpful.GetMoreThings.GetEnumerator();
bool more = true;
while (more) {
try {
more = iterator.MoveNext();
}
catch (Exception e) {
//crash, burn
}
if (more)
yield return iterator.Current;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1087 次 |
| 最近记录: |