gpt4 book ai didi

c# - 如果在 c# 中该类的任何方法中发生,则创建一个捕获异常的方法

转载 作者:行者123 更新时间:2023-11-30 14:44:50 25 4
gpt4 key购买 nike

我有一个 Demo 类,它有以下四种方法 Add()Update()Delete()Get()

这些方法链接在一起如下:

bool isSuccess = this.Get(1)
.Update(200) //new product price

现在,我想实现 CatchError() 方法,该方法将捕获 Exception if 发生在上述任何方法中。

代码如下所示:

bool isSuccess = this.Get(1)
.Update(200); //new product price
.CatchError();

不知道如何实现CatchError()方法。

很乐意提供额外的信息来适本地帮助回答问题。

最佳答案

就像我在评论中写的那样,我会尝试创建一个 CatchError() 方法,您可以在其中将 Action 作为参数:

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

您的 CatchError() 方法如下所示:

private static bool CatchError(Action action)
{
try
{
action();
return true;
}
catch (Exception)
{
return false;
}
}

关于c# - 如果在 c# 中该类的任何方法中发生,则创建一个捕获异常的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56952283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com