是否可以确定PostError中的调用方法名称“Eat Pizza”? 我想我可以将“EatPizza”作为参数之一传递,但这需要每次方法名称更改时进行更改(不必要的维护)。但后来,我什至无法在“EatPizza”的上下文中找到方法名称“EatPizza”(使用 stacktrace、getframe、getmethod)。
public void EatPizza(Pizza p){
if(p==null){ //A arbitrary made up error
Utilities.PostError();
}
else{
p.Slices -= 1;
}
}
...
public void PostError(){
//Basically posting to database the name of the method
//Tried this, didn't work: (new StackTrace(true)).GetFrame(5).GetMethod().Name
//Is it possible to determine the calling method name "Eat Pizza" in this context?
}
当我在 StackTrace.GetFrame 中尝试不同的值(0 到 StackTrace.FrameCount-1)时,当我只想“EatPizza”时,我得到以下值:
.ctor
ThreadStart
Main
_nExecuteAssembly
RunUsersAssemblyDebugInZone
最佳答案
您创建 StackTrace
对象的方向是正确的,但您似乎误解了 GetFrame
的参数。帧从最底部帧开始编号,因此:
GetFrame(0)
将返回PostError
GetFrame(1)
将返回PostError
的调用者
所以试试这个:
var trace = new StackTrace(true);
WriteToDB(trace.GetFrame(1).GetMethod().Name);
就我个人而言,我更愿意获取整个堆栈跟踪而不仅仅是调用者,所以我会这样做:
var trace = new StackTrace(true);
WriteToDB(trace.ToString());
关于c# - 获取调用方法的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5667386/