テンプレート化されたデリゲート
-
03-07-2019 - |
質問
次のコードパターンがあります:
void M1(string s, string v)
{
try
{
// Do some work
}
catch(Exception ex)
{
// Encapsulate and rethrow exception
}
}
唯一の違いは、メソッドへの戻り値の型とパラメーターの数と型が異なる場合があることです。
" Do some work"を除くすべてのコードを処理する汎用/テンプレート化されたメソッドを作成したい一部、どのように達成することができます。
解決
アクションが好き
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);
}
所属していません StackOverflow