使用 yield 时在 try/catch 中包装对迭代器的调用

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)

在调用方法中,我需要将调用包装GetMoreThingstry/catchyield 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 之类的东西

有什么建议吗?

sq3*_*33G 5

这里的两个答案都是正确的。这个没有内置快捷方式,您需要在一个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)