【发布时间】:2023-12-09 18:33:02
【问题描述】:
我想知道使用 Generics Func 或任何其他方式避免重复某些重复代码结构的最佳方法是什么。 作为一个实际的例子,我需要调用 20 个不同的 WCF 方法,但我希望有代码来处理异常。
假设这是 wcf 代理
class ClassWithMethodsToCall // say wcf proxy
{
public Out1 GetOut1(In1 inParam) { return null; } // would have some spesific implementation
public Out2 GetOut2(In2 inParam) { return null; }
public Out3 GetOut3(In3 inParam) { return null; }
}
class Out1 { } // some specific data structure
class In1 { } // some specific data structure
class Out2 { } // some specific data structure
class In2 { } // some specific data structure
class Out3 { } // some specific data structure
class In3 { } // some specific data structure
我创建了以下内容以进行单一错误处理
class CallerHelperWithCommonExceptionHandler
{
public Tout Call<Tout, Tin>(Tin parameters, Func<Tin,Tout> wcfMethodToCall)
{
try
{
return wcfMethodToCall(parameters);
}
catch (Exception ex)
{
// do what ever
throw;
}
}
}
我使用它:
var callerHelper = new CallerHelperWithCommonExceptionHandler();
var theFunctionsToCall = new ClassWithMethodsToCall();
var in1 = new In1(); // init as appropriate
var ou1 = callerHelper.Call<Out1, In1>(in1, theFunctionsToCall.GetOut1);
var in2 = new In2(); // init as appropriate
var ou2 = callerHelper.Call<Out2, In2>(in2, theFunctionsToCall.GetOut2);
// and so on
有没有更好更优雅的方式?面向对象方式的替代方案,模板设计模式?
谢谢大家
【问题讨论】:
-
这根本不是重复。你的班级
ClassWithMethodsToCall对我来说很好。你的CallerHelperWithCommonExceptionHandler让 IMO 变得更糟。 -
同意,看起来更糟。
-
你正在寻找的可能是面向方面的编程短 AOP 这里是一个例子ayende.com/blog/3474/logging-the-aop-way
-
好吧,如果没有 CallerHelperWithCommonExceptionHandler,我必须为 ClassWithMethodsToCall 的每个方法调用重复 try catch。如果我有 20 种方法,我会为每个方法重复相同的错误处理代码块。
标签: c# generics func code-duplication