1

次のコードパターンがあります。

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

唯一の違いは、戻り値の型と、メソッドへのパラメーターの数と型が異なる可能性があることです。

「いくつかの作業を行う」部分を除くすべてのコードを処理する汎用/テンプレート化されたメソッドを作成したいのですが、どうすれば実現できますか。

4

1 に答える 1

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);
}
于 2008-10-03T19:09:38.070 に答える