문제

다음과 같은 코드 패턴이 있습니다.

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top