问题
I'm using this helper to resolve the name of the method that is currently being executed for logging purposes.
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentMethod()
{
StackTrace st = new StackTrace();
StackFrame sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
This is the string that is returned <Frequency>b__46
" What does the b__46 mean? And is there a way to just retrieve the word "Frequency?"
This is calling the helper.
return ProxyCallWrapper.Execute<bool, IBackendJob>((backend, header) =>
{
header.CorrelationID = CorrelationID;
logger.LogInfo(string.Format("### BSL CALL from {0} by {1} : CorrelationID: {2}", this.ToString(), GetCurrentMethod() ,header.CorrelationID));
return backend.AddJob(header, jobId);
});
回答1:
The method is probably being called from a lambda expression. The C# compiler actually converts lambdas to hidden methods inside your class. These methods have special compiler-generated names, like the <Frequency>b__46
you're seeing. I think you'll find if you look at GetFrame(2)
you'll see the name you expect. Your function could ignore lambdas by looping up the stack until it finds a valid method name (you can check the method descriptor's IsSpecialName property for that).
The compiler also generates hidden methods with special names for auto property getters and setters, event add/remove handlers, and some other cases (you won't encounter these since these auto-generated methods can't call your GetCurrentMethod()
). But note also that manual property getters and setters have "special" names like get_PropertyName()
, and you may see those if you have a property whose code calls GetCurrentMethod()
.
回答2:
<Frequency>b__46
is the name of the method that called GetCurrentMethod()
.
Since you are calling the method from a lambda, you have to accept that the name of the lambda is beyond your control.
来源:https://stackoverflow.com/questions/21564769/stackframe-getmethod-name