那么对此的一些功能解决方案呢?请注意,我不会吞下异常并使用throw;
语句,这将重新引发异常并保持其原始堆栈跟踪。不要默默地吞下异常——这被认为是一种非常糟糕的做法,调试代码会变得很糟糕。
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;
}
}