c# - 获取调用方法的方法?

标签 c# methods stack-trace stack-frame getmethod

是否可以确定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/

相关文章:

c++ - cppunit:setUp() 和 tearDown()

java - printf,说,getName setName

c++ - backtrace_symbols 无法打印导致信号的函数

iOS 堆栈跟踪不准确

c# - 使用 EPPlus 将文本添加到 Excel 电子表格中的合并单元格

c# - 如何确定 "DirectoryEntry"是否找到了我的用户?

c# - 在 C# 中获取 Google Sheets API v4 中的最后一列

c# - 将属性从母版页传递到 aspx 页面

methods - 如果我在序列图中有一个对象用户,并且我想让该对象与界面交互,我应该使用它自己的函数吗?

c# - 写入堆栈跟踪