2008-10-03 41 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); 
}