什么一些功能性的解决方案呢?注意我没有吞下异常,并使用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;
}
}
你能证明你的代码...... –
为什么不干脆的try/catch每发送异常普通的静态函数? –
@JoelEtherton我该怎么去做这件事,你有没有例子? –