我也会去StackFrame
。我正在发布@Tigran 答案的扩展(因为您要求在try{...}catch{...}
块内更明确地使用),所以如果这有助于您理解用法,请接受他的回答,而不是我的:
try
{
int a = 0;
var r = 1 / a;
}
catch (Exception ex)
{
throw new Exception(
String.Format("{0} Method name: {1}",
ex.Message,
GetCallingMethodName()),
ex);
}
GetCallingMethodName
: _
private static string GetCallingMethodName()
{
const int iCallDeepness = 1; //DEEPNESS VALUE, MAY CHANGE IT BASED ON YOUR NEEDS
System.Diagnostics.StackTrace stack = new System.Diagnostics.StackTrace(false);
System.Diagnostics.StackFrame sframe = stack.GetFrame(iCallDeepness);
return sframe.GetMethod().Name;
}
PS @Tigran,如果您认为不需要此答案,我将删除此答案。