如何找到调用当前方法的方法? [英] How can I find the method that called the current method?
本文介绍了如何找到调用当前方法的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
登录C#时,如何得知调用当前方法的方法名?我对 System.Reflection.MethodBase.GetCurrentMethod()
了如指掌,但我想在堆栈跟踪中更进一步.我已经考虑过解析堆栈跟踪,但我希望找到一种更清晰、更明确的方法,例如 Assembly.GetCallingAssembly()
但对于方法.
When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod()
, but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly()
but for methods.
推荐答案
试试这个:
using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
单线:
(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name
来自Get Calling Method using Reflection [C#].
这篇关于如何找到调用当前方法的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文