gpt4 book ai didi

c# - 如何在多种方法中很好地使用try catch?

转载 作者:太空狗 更新时间:2023-10-30 00:19:14 25 4
gpt4 key购买 nike

对不起,如果我的问题很愚蠢,但我有这样的代码:

public Object1 Method1(Object2 parameter)
{
try
{
return this.linkToMyServer.Method1(parameter);
}
catch (Exception e)
{
this.Logger(e);
}

return null;
}

public Object3 Method2(Object4 parameter)
{
try
{
return this.linkToMyServer.Method2(parameter);
}
catch (Exception e)
{
this.Logger(e);
}

return null;
}

/* ... */

public ObjectXX Method50(ObjectXY parameter)
{
try
{
return this.linkToMyServer.Method50(parameter);
}
catch (Exception e)
{
this.Logger(e);
}

return null;
}

我想你看到了模式。有没有一种很好的方法让只有一个 try catch 并在这个 try catch 中传递一个通用方法?

本能地我会使用委托(delegate),但委托(delegate)必须具有相同的签名,对吧?

提前致谢。

问候。

最佳答案

只要您看到这样的代码,您就可以申请 Template Method Pattern .

可能是这样的:

private TResult ExecuteWithExceptionHandling<TParam, TResult>(TParam parameter, Func<TParam, TResult> func)
{
try
{
return func(parameter);
}
catch (Exception e)
{
this.Logger(e);
}
return default(TResult);
}

public Object1 Method1(Object2 parameter)
{
return ExecuteWithExceptionHandling(parameter, linkToMyServer.Method1);
}

public Object3 Method2(Object4 parameter)
{
return ExecuteWithExceptionHandling(parameter, linkToMyServer.Method2);
}

等等……

关于c# - 如何在多种方法中很好地使用try catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23423043/

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