我有以下代码模式:

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

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

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

有帮助吗?

解决方案

我喜欢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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top