.net 模板代表

.net 模板代表,.net,generics,delegates,template-method-pattern,.net,Generics,Delegates,Template Method Pattern,我有以下代码模式: void M1(string s, string v) { try { // Do some work } catch(Exception ex) { // Encapsulate and rethrow exception } } 唯一的区别是返回类型以及方法的参数数量和类型可能会有所不同 我想创建一个通用/模板化方法来处理除“做一些工作”部分之外的所有代码,如何实现它。我喜欢这个动作 public static void Meth

我有以下代码模式:

void M1(string s, string v)
{
  try
  {
    // Do some work
  }
  catch(Exception ex)
  {
    // Encapsulate and rethrow exception
  }
}
唯一的区别是返回类型以及方法的参数数量和类型可能会有所不同

我想创建一个通用/模板化方法来处理除“做一些工作”部分之外的所有代码,如何实现它。

我喜欢这个动作

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);
}
我喜欢这个动作

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);
}

这对某些人来说可能是显而易见的,但你仍然应该为目标语言添加一个标记…对某些人来说可能是显而易见的,但你仍然应该为目标语言添加一个标记。。。