Pregunta

Tengo el siguiente patrón de código:

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

La única diferencia es que el tipo de retorno y el número y los tipos de parámetros de los métodos pueden variar.

Quiero crear un método genérico / con plantilla que maneje todo el código, excepto el " Hacer algún trabajo " parte, cómo se puede lograr.

¿Fue útil?

Solución

Me gusta la acción

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top