【发布时间】:2012-05-07 11:44:23
【问题描述】:
我想干燥我的源代码。假设我有一些主要在一行中不同的功能 - 我怎么能做到这一点??
public Result foo (int x, int y, int z){
Log.Say("Foo started!"); <<< DIFFERENCE
DoSomeMagic();
try {
result = controller.foo(x, y, z); <<< DIFFERENCE
} catch (Exception){
Log.Say("Something went terribly wrong");
}
return result;
}
public Result bar (Person a, string whatever){
Log.Say("Bar started!"); <<< DIFFERENCE
DoSomeMagic();
try {
result = controller.bar(a, whatever); <<< DIFFERENCE
} catch (Exception) {
Log.Say("Something went terribly wrong");
}
return result;
}
这让我发疯了,因为它不可能那么难吗?我现在对各种方法感到困惑;到目前为止,我试图与代表一起做, Func、Lambda 表达式、匿名函数,但我就是无法让它工作(我想我需要休息一下)。
public Result handler (Func callbackMethodWithArgs) {
Result result = null;
Log.Say(method + " started!");
DoSomeMagic();
try {
result = invoke(callbackMethodWithArgs) as Result;
} catch (Exception) {
Log.Say("Something went terribly wrong");
}
return result;
}
public Result foo (int x, int y, int z) {
return handler(controller.foo(x, y, z));
}
public Result bar (Person a, string whatever) {
return handler(controller.bar(a, whatever);
}
作为补充,可以使用匿名函数真的很棒,比如
public Result foo (int x, int y, int z) {
return handler(delegate () {
controller.foo(x, y, z));
doSomethingOther();
});
}
有什么建议吗??谢谢! (我阅读了许多关于类似主题的问题,但我没有找到任何解决问题的方法 - 所以我认为它可能是重复的 - 如果是这样,我很抱歉)
【问题讨论】:
标签: c# delegates lambda dry anonymous-function