相关疑难解决方法(0)

包装IEnumerable并捕获异常

我有一堆可以Process()对象的类,并返回自己的对象:

public override IEnumerable<T> Process(IEnumerable<T> incoming) { ... }
Run Code Online (Sandbox Code Playgroud)

我想编写一个可以包装其中一个处理器的处理器类,并记录包装Process()方法可能抛出的任何未捕获的异常.我的第一个想法是这样的:

public override IEnumerable<T> Process(IEnumerable<T> incoming) {
    try {
        foreach (var x in this.processor.Process(incoming)) {
            yield return x;
        }
    } catch (Exception e) {
        WriteToLog(e);
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为CS1626:不能在带有catch子句的try块的主体中​​产生值.

所以我想写一些概念上等同但编译的东西.:-)我有这个:

public override IEnumerable<T> Process(IEnumerable<T> incoming) {
    IEnumerator<T> walker;
    try {
        walker = this.processor.Process(incoming).GetEnumerator();
    } catch (Exception e) {
        WriteToLog(e);
        throw;
    }

    while (true) {
        T value;
        try {
            if (!walker.MoveNext()) {
                break;
            }
            value = …
Run Code Online (Sandbox Code Playgroud)

c# ienumerable exception wrapper

11
推荐指数
3
解决办法
5911
查看次数

标签 统计

c# ×1

exception ×1

ienumerable ×1

wrapper ×1