Question

J'ai le motif de code suivant:

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

La seule différence est que le type de retour et le nombre et les types de paramètres des méthodes peuvent varier.

Je souhaite créer une méthode générique / basée sur un modèle qui gère l'intégralité du code, à l'exception de l'option "Effectuer des travaux". partie, comment peut-il être réalisé.

Était-ce utile?

La solution

J'aime l'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);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top