我有幾個方法執行相同的設置代碼,然後一些清理代碼。變化之間的東西。我可以這樣做:如何用模式或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