Domanda

Ho il seguente modello di codice:

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

L'unica differenza è che il tipo di restituzione e il numero e i tipi di parametri dei metodi possono variare.

Voglio creare un metodo generico / basato su modelli che gestisca tutto il codice ad eccezione di " Do some work " parte, come può essere raggiunto.

È stato utile?

Soluzione

Mi piace l'azione

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);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top