我有几个方法执行相同的设置代码,然后一些清理代码。变化之间的东西。我可以这样做:如何用模式或lambda语法实现这个?
void method1()
{
var x = DoSetupStuff();
// Method 1 specific code that uses x
DoCleanupStuff(x);
}
void method2()
{
var x = DoSetupStuff();
// Method 2 specific code that uses x
DoCleanupStuff(x);
}
但我宁愿做一些事情,我不必每次都调用setup和cleanup方法。也许像一个调用方法特定的东西可以传入?
void SetupAndCleanup(method-specific-code)
{
// Setup code here
int x = 1;
// method-specific code injected here.
// note that it uses x.
// cleanup code here
x = 0;
}
的方法1,方法2的方式工作得很好,我只是游荡,如果有改善,或使其更加优雅的方式。
即使他只是使用动作,他也不会在lambda表达式中访问x。 – 2011-01-06 17:15:33