模板代表



我有以下代码模式:

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

唯一的区别是返回类型以及方法的参数数量和类型可能会有所不同。

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

我喜欢Action

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

相关内容

  • 没有找到相关文章

最新更新