【发布时间】:2016-05-22 04:39:06
【问题描述】:
我需要在我作为迭代器(使用yield)实现的方法中执行一些繁重、有些脆弱的逻辑:
public IEnumerable<Things> GetMoreThings() {
while (goodStuffHappens()) {
Things moreThingsIWant = TemptFateAgain();
if (moreThingsIWant.Any())
yield return moreThingsIWant;
}
}
在调用方法中,我需要将对GetMoreThings的调用包装在try/catch和yield return结果中:
try {
foreach (Things thing in Helpful.GetMoreThings())
yield return thing;
}
catch (Exception e) {
//crash, burn
}
发起者会立即意识到这是不可能的——there is no such thing as a yield inside a try/catch block(仅限try/finally)。
有什么建议吗?
【问题讨论】:
-
你真的想忽略异常,还是
catch块中有一些你没有显示的代码? -
是的,那里有重要的代码
标签: c# try-catch yield-return