You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何为Demo类的链式调用实现CatchError()异常捕获方法

实现链式调用的CatchError()方法

要实现你想要的CatchError()方法,核心是结合链式调用的特性和异常状态追踪/延迟执行,下面给你两种实用的方案,你可以根据自己的需求选择:

方案一:在Demo类内部追踪异常状态(简单直接)

这个方案让Demo类本身维护一个异常状态,所有业务方法(Get/Update/Add/Delete)执行时捕获异常并存储,最后通过CatchError()处理异常并返回操作结果。

完整代码示例

public class Demo
{
    // 私有字段存储最近一次操作的异常
    private Exception _lastException;

    public Demo Get(int id)
    {
        try
        {
            // 这里替换为你的Get方法实际逻辑
            Console.WriteLine($"执行Get操作,ID: {id}");
            // 模拟异常场景(可根据实际业务移除)
            if (id <= 0)
                throw new ArgumentException("ID不能为非正数");
        }
        catch (Exception ex)
        {
            // 捕获异常并存储
            _lastException = ex;
        }
        return this; // 返回当前实例,维持链式调用
    }

    public Demo Update(int price)
    {
        try
        {
            // 这里替换为你的Update方法实际逻辑
            Console.WriteLine($"执行Update操作,价格: {price}");
            // 模拟异常场景
            if (price < 0)
                throw new ArgumentOutOfRangeException(nameof(price), "价格不能为负数");
        }
        catch (Exception ex)
        {
            _lastException = ex;
        }
        return this;
    }

    // Add和Delete方法遵循同样的模式
    public Demo Add()
    {
        try
        {
            Console.WriteLine("执行Add操作");
            // Add逻辑...
        }
        catch (Exception ex)
        {
            _lastException = ex;
        }
        return this;
    }

    public Demo Delete(int id)
    {
        try
        {
            Console.WriteLine($"执行Delete操作,ID: {id}");
            // Delete逻辑...
        }
        catch (Exception ex)
        {
            _lastException = ex;
        }
        return this;
    }

    // 你需要的CatchError方法
    public bool CatchError()
    {
        if (_lastException != null)
        {
            // 这里实现异常处理逻辑(比如日志记录、告警等)
            Console.WriteLine($"捕获到异常: {_lastException.Message}");
            // 可选:重置异常状态,避免影响后续链式调用
            _lastException = null;
            return false; // 表示操作失败
        }
        return true; // 所有操作执行成功
    }
}

调用方式(和你期望的完全一致)

// 正常执行,返回true
bool isSuccess = new Demo().Get(1).Update(200).CatchError();

// 触发异常,CatchError捕获并返回false
bool isFailed = new Demo().Get(-5).Update(200).CatchError();

方案二:延迟执行+统一捕获(保留原方法异常行为)

如果你不想修改原有方法的异常抛出逻辑,希望所有链式操作在CatchError时才执行,并统一捕获异常,可以用一个包装类来收集操作,最后一次性执行并处理异常。

完整代码示例

public class Demo
{
    // 原方法返回操作包装类,用于收集后续操作
    public DemoOperation Get(int id)
    {
        var operation = new DemoOperation();
        operation.AddAction(() =>
        {
            // 你的Get原逻辑,保持异常抛出行为
            Console.WriteLine($"执行Get操作,ID: {id}");
            if (id <= 0)
                throw new ArgumentException("ID不能为非正数");
        });
        return operation;
    }
}

// 操作包装类,负责收集链式调用的所有操作
public class DemoOperation
{
    private readonly List<Action> _operations = new List<Action>();

    internal void AddAction(Action action)
    {
        _operations.Add(action);
    }

    // 链式调用的Update方法,添加操作到列表
    public DemoOperation Update(int price)
    {
        _operations.Add(() =>
        {
            Console.WriteLine($"执行Update操作,价格: {price}");
            if (price < 0)
                throw new ArgumentOutOfRangeException(nameof(price), "价格不能为负数");
        });
        return this;
    }

    // Add和Delete方法同理
    public DemoOperation Add()
    {
        _operations.Add(() => Console.WriteLine("执行Add操作"));
        return this;
    }

    public DemoOperation Delete(int id)
    {
        _operations.Add(() => Console.WriteLine($"执行Delete操作,ID: {id}"));
        return this;
    }

    // 统一执行并捕获异常
    public bool CatchError()
    {
        try
        {
            // 依次执行所有收集的操作
            foreach (var op in _operations)
            {
                op();
            }
            return true;
        }
        catch (Exception ex)
        {
            // 处理异常
            Console.WriteLine($"捕获到异常: {ex.Message}");
            return false;
        }
    }
}

调用方式

bool isSuccess = new Demo().Get(1).Update(200).CatchError();

方案选择建议

  • 如果你的原有业务方法原本就不依赖异常抛出(或者可以接受改为内部捕获),方案一更简单,不需要额外的类,代码结构更紧凑。
  • 如果需要保留原有方法的异常抛出逻辑,或者希望批量执行操作后统一处理异常,方案二更合适。

内容的提问来源于stack exchange,提问作者Bijay Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:06:30