これに対する機能的な解決策はどうですか?throw;
元のスタック トレースを保持したまま例外を再スローする例外と use ステートメントを飲み込まないことに注意してください。黙って例外を飲み込まないでください。これは非常に悪い習慣であると考えられており、デバッグ コードは恐ろしいものになります。
void Main()
{
WrapFunctionCall( () => DoSomething(5));
WrapFunctionCall( () => DoSomethingDifferent("tyto", 4));
}
public void DoSomething(int v){ /* logic */}
public void DoSomethingDifferent(string v, int val){ /* another logic */}
public void WrapFunctionCall(Action function)
{
try
{
function();
}
catch(Exception e)
{
//a BUNCH of logic that is the same for all functions
throw;
}
}
何らかの値を返す必要がある場合、WrapFunctionCall
メソッドの署名が変更されます
void Main()
{
var result = WrapFunctionCallWithReturn( () => DoSomething(5));
var differentResult = WrapFunctionCallWithReturn( () => DoSomethingDifferent("tyto", 4));
}
public int DoSomething(int v){ return 0; }
public string DoSomethingDifferent(string v, int val){ return "tyto"; }
public T WrapFunctionCallWithReturn<T>(Func<T> function)
{
try
{
return function();
}
catch(Exception e)
{
//a BUNCH of logic that is the same for all functions
throw;
}
}