StackFrame.GetMethod().Name [英] StackFrame.GetMethod().Name
问题描述
我正在使用此帮助程序来解析当前出于日志记录目的而执行的方法的名称.
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;
}
这是返回的字符串<Frequency>b__46
" b__46是什么意思? 并有一种方法可以只检索频率"吗?
" What does the b__46 mean? And is there a way to just retrieve the word "Frequency?"
这正在呼叫助手.
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);
});
推荐答案
该方法可能是从lambda表达式中调用的. C#编译器实际上将lambda转换为类中的隐藏方法.这些方法具有特殊的编译器生成的名称,例如您看到的<Frequency>b__46
.我想您会发现,如果您查看GetFrame(2)
,将会看到所需的名称.您的函数可以通过循环堆栈直到找到有效的方法名称来忽略lambda(您可以检查方法描述符的
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).
编译器还会为自动属性获取器和设置器,事件添加/删除处理程序以及其他一些情况生成具有特殊名称的隐藏方法(您不会遇到这些,因为这些自动生成的方法无法调用您的GetCurrentMethod()
).但也请注意,手动属性获取器和设置器具有特殊"名称,如get_PropertyName()
,如果您拥有一个其代码调用GetCurrentMethod()
的属性,则可能会看到它们.
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()
.
这篇关于StackFrame.GetMethod().Name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!