C# 使用yield时在try/catch中包装对迭代器的调用
我需要在我作为迭代器实现的方法(使用C# 使用yield时在try/catch中包装对迭代器的调用,c#,try-catch,yield-return,C#,Try Catch,Yield Return,我需要在我作为迭代器实现的方法(使用yield)中执行一些沉重的、有些脆弱的逻辑: 发起人将立即意识到这是不可能的-(只有尝试/最终) 有什么建议吗?将有用的.GetMoreThings()调用和枚举与收益率分开放置: public IEnumerable<Things> GetMoreThings() { while (goodStuffHappens()) { Things moreThingsIWant = TemptFateAgain();
yield
)中执行一些沉重的、有些脆弱的逻辑:
发起人将立即意识到这是不可能的-(只有尝试
/最终
)
有什么建议吗?将
有用的.GetMoreThings()
调用和枚举与收益率
分开放置:
public IEnumerable<Things> GetMoreThings() {
while (goodStuffHappens()) {
Things moreThingsIWant = TemptFateAgain();
if (moreThingsIWant.Any())
yield return moreThingsIWant;
}
}
try {
var results = Helpful.GetMoreThings().ToList();
}
catch (Exception e) {
//crash, burn
}
foreach (Things thing in results)
yield return thing;
差不多吧
如果你需要它来偷懒,代码会变得非常糟糕。您不能再使用foreach
。您需要手动编写迭代循环,代码大小会爆炸成20行难以辨认的混乱。我知道是因为我昨天做的。你可以使用,也可以复制。代码可能如下所示:
return Helpful.GetMoreThings().Catch((Exception e) =>
{
// crash, burn
return null;
}
这里的两个答案都是正确的。这个函数没有内置的快捷方式,您需要在
while
而不是for
循环中分离迭代器,以便在调用枚举器.MoveNext()
和使用枚举器.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;
}
IEnumerator iterator=help.GetMoreThings.GetEnumerator();
布尔莫尔=真;
而(更多){
试一试{
more=iterator.MoveNext();
}
捕获(例外e){
//撞车,烧伤
}
如果(更多)
产生返回迭代器.Current;
}
是的,我需要它是懒惰的。否则,我很难找到这样设计它的好理由。然后,按照最后一段所说的做:将foreach扩展为手动编写的循环。然后,您可以使用catch-guard调用MoveNext(),并在不使用catch的情况下进行屈服。您是真的想忽略这个异常,还是在catch
块中有一些代码没有显示出来?是的,其中有重要的代码源代码实际上是@usr的回答中提到的20条难以辨认的混乱行。
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;
}