gpt4 book ai didi

.net - 如何避免异常捕获 .NET 中的复制粘贴

转载 作者:行者123 更新时间:2023-12-04 10:58:18 26 4
gpt4 key购买 nike

使用 .NET 框架我有一个服务,其中包含一组可以生成多种类型异常的方法:MyException2、MyExc1、Exception... 为了为所有方法提供适当的工作,每个方法都包含以下部分:

[WebMethod]
void Method1(...)
{
try
{
... required functionality
}
catch(MyException2 exc)
{
... process exception of MyException2 type
}
catch(MyExc1 exc)
{
... process exception of MyExc1 type
}
catch(Exception exc)
{
... process exception of Exception type
}
... process and return result if necessary
}

在每个服务方法中拥有完全相同的东西(每个方法都有不同的参数集)和完全相同的异常处理功能是非常无聊的......

是否有可能将这些捕获部分“分组”并仅使用一行(类似于 C++ 宏)? .NET 4.0 中的新内容可能与此主题有关?

谢谢。

附言欢迎任何想法。

最佳答案

如果异常处理为完全一样在您的所有方法中,您都可以执行以下操作:

void CallService(Action method)
{
try
{
// Execute method
method();
}
catch(MyException2 exc)
{
... process exception of MyException2 type
}
catch(MyExc1 exc)
{
... process exception of MyExc1 type
}
catch(Exception exc)
{
... process exception of Exception type
}
}

然后,您可以重写客户端代码来执行以下操作:
int i = 3;
string arg = "Foo";
this.CallService( () => this.Method1(i) );
this.CallService( () => this.Method2(arg, 5) );

这允许您的 Method1 和 Method2 方法简单地:
void Method1(int arg)
{
// Leave out exception handling here...
... required functionality
... process and return result if necessary
}

void Method2(string stringArg, int intArg)
{
// Leave out exception handling here...
... required functionality
... process and return result if necessary
}

关于.net - 如何避免异常捕获 .NET 中的复制粘贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3064463/

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