2011-03-10 27 views
1


我剛剛遇到了「中間孔」模式,並認爲我可以使用它刪除一些重複的代碼,特別是當我嘗試對不同的方法進行基準測試並使用相同的代碼時每種方法之前和之後。使用「中間孔」模式

我能夠獲得與下面的代碼工作的基礎知識。我開始與StartingMethod,其主要目標是調用MainMethod1 & MainMethod2,但它通過PrePostMethod這樣做。

我現在想知道的是如何傳遞參數並獲得返回值。任何幫助都會很棒。

謝謝。

代碼:

 
public static class HoleInTheMiddle 
    { 
     public static void StartingMethod() 
     { 
      PrePostMethod(MainMethod1); 
      PrePostMethod(MainMethod2); 
     } 

     public static void PrePostMethod(Action someMethod) 
     { 
      Debug.Print("Pre"); 

      someMethod(); 

      Debug.Print("Post"); 
     } 

     public static void MainMethod1() 
     { 
      Debug.Print("This is the Main Method 1"); 
     } 

     public static void MainMethod2() 
     { 
      Debug.Print("This is the Main Method 2"); 
     } 
    } 

回答

2

你可以做一個通用的方法,並使用一個通用的委託:

public static TResult PrePostMethod<T1, T2, TResult>(Func<T1, T2, TResult> someMethod, T1 a, T2 b) 
{ 
    Debug.Print("Pre"); 

    var result = someMethod(a, b); 

    Debug.Print("Post"); 

    return result; 
} 

你所需要的參數每個號碼單獨的泛型重載。

+0

謝謝,這很好。你能推薦任何特定的閱讀材料來理解這一點嗎?這與泛型或Lambda表達式有關嗎? – 2011-03-10 03:02:59

+0

這使用泛型,但不使用lambda表達式。閱讀MSDN。 – SLaks 2011-03-10 03:20:50