2008-10-03 27 views
1

我有以下片碼模式的:模板化代表

void M1(string s, string v) 
{ 
    try 
    { 
    // Do some work 
    } 
    catch(Exception ex) 
    { 
    // Encapsulate and rethrow exception 
    } 
} 

唯一的區別是,返回類型和參數,在將方法的數目和類型可以變化。

我想創建一個通用/模板化方法來處理除「做一些工作」部分以外的所有代碼,它如何實現。

+0

這可能是明顯一些,但還是應該添加一個標籤爲目標語言... – PhiLho 2008-10-03 20:18:08

回答

1

我喜歡行動

public static void Method(Action func) 
{ 
    try 
    { 
     func(); 
    } 
    catch (Exception ex) 
    { 
     // Encapsulate and rethrow exception 
     throw; 
    } 
} 



public static void testCall() 
{ 
    string hello = "Hello World"; 

    // Or any delgate 
    Method(() => Console.WriteLine(hello)); 

    // Or 
    Method(() => AnotherTestMethod("Hello", "World")); 

} 

public static void AnotherTestMethod(string item1, string item2) 
{ 
    Console.WriteLine("Item1 = " + item1); 
    Console.WriteLine("Item2 = " + item2); 
}