gpt4 book ai didi

c# - 如何围绕方法调用添加通用功能?

转载 作者:行者123 更新时间:2023-11-30 22:42:20 25 4
gpt4 key购买 nike

有问题的代码是由机器人(CodeSmith)编写的,维护起来很痛苦。它看起来有点类似于:

public AddressProgramTemplate GetById(System.Int32 _id) {
try {
return Service.GetById(_id);
} catch (FaultException<ErrorInfo> ex) {
throw new ProxyServerBusinessException(ex.Detail);
} catch (FaultException) {
throw new ProxyServerBusinessException(null);
} catch (EndpointNotFoundException ex) {
throw new ProxyServerTechnicalException<EndpointNotFoundException>(ex);
} catch (CommunicationObjectFaultedException ex) {
throw new ProxyServerTechnicalException<CommunicationObjectFaultedException>(ex);
} catch (CommunicationException ex) {
throw new ProxyServerTechnicalException<CommunicationException>(ex);
} catch (ObjectDisposedException ex) {
throw new ProxyServerTechnicalException<ObjectDisposedException>(ex);
} catch (TimeoutException ex) {
throw new ProxyServerTechnicalException<TimeoutException>(ex);
}
}

您可以猜到,它是一个客户端 WCF 代理代码,所有这些行都针对存在的每个服务方法(并且有很多)重复。 robot的好处是我的悲哀,于是我开始重构它。首先,将异常逻辑和处理委托(delegate)给 Microsoft Enterprise Library,并将公共(public)代码迁移到基类:

public TResult WrapServiceMethod<TResult>(Func<TResult> serviceMethod) {
TResult result = default(TResult);
try {
result = serviceMethod();
} catch (Exception ex) {
bool rethrow = ExceptionManager.HandleException(ex, ExceptionPolicyNames.ClientRequestPolicy);
if (rethrow) throw;
}
return result;
}

到目前为止一切顺利,丑陋的 try/catch 堆变成了整洁的一行:

return WrapServiceMethod<AddressProgramTemplate>(() => Service.GetById(_id));

还介绍了一点努力和无效的方法。当服务调用使用 out 参数时问题就来了:

public void GetPeriod(AddressProgram program, out DateTime startDate, out DateTime endDate){
WrapServiceMethod(() => Service.GetPeriod(program, out startDate, out endDate));
}

导致“无法在匿名方法、lambda 表达式或查询表达式中使用 ref 或 out 参数‘endDate’”,我理解 why .

理想情况下,我希望能够定义自定义运算符 block ,例如 while() 或 using(),这样我就可以编写

wrapexception { ... }

从此过上幸福的生活,但我认为 .NET 无法实现这一技巧。假设重写所有不带 out 参数的服务方法是最后的手段,我还有其他选择吗?

最佳答案

听起来您正在寻找面向方面的编程库,例如 PostSharp。

您可以创建异常处理程序,在编译后根据您指定的规则插入到您的 IL 中,这些规则可以执行诸如捕获异常、日志记录、跟踪等操作。

这样做的好处是您只编写一次切面,然后将其应用于多个方法。这些方法不会被与手头特定任务无关的代码混杂在一起,因为方面会处理异常处理等横切关注点。

查看 http://www.sharpcrafters.com/solutions/monitoring#exception-monitoring 中的示例其中显示了如何处理异常。

关于c# - 如何围绕方法调用添加通用功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4466353/

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