Skip to main content
 首页 » 编程设计

c#之获取最后调用的方法的名称

2024年02月20日13jackei

我有以下代码:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
        InitializeComponent(); 
        try 
        { 
            this.CheckValue(true); // call method 
        } 
        catch(Exception ex) 
        { 
            // how to get here name of last called method 
        } 
    } 
 
    public int CheckValue(bool sender) 
    { 
        var qwe = int.Parse("qwe"); // invoke an exception 
 
        return 0; 
    } 
} 

我需要在“catch block ”中获取上次调用方法的名称(在本例中为“CheckValue”),但它返回被调用的方法是“StringToNumber”。

我尝试使用 StackTrace 获取它:

stackTrace.GetFrame(1).GetMethod().Name; -> "Main" 
MethodBase.GetCurrentMethod(); -> "Void .ctor()" 
ex.TargetSite.Name; -> "StringToNumber" 

这有可能吗?

请您参考如下方法:

简答:

是的,你可以!!!


我只是尝试使用扩展方法,这里的技巧是获取所需类的最后一帧,否则它将获取 mscorlib 程序集的方法。所以开始吧:

public static string GetLastCalledMethod<T>(this Exception ex) 
{ 
    var stackTrace = new System.Diagnostics.StackTrace(ex); 
    var lastFrame = stackTrace.GetFrames().FirstOrDefault(frame => frame.GetMethod().DeclaringType.FullName == typeof(T).FullName); 
 
    string methodName = string.Empty; 
    if (lastFrame != null) 
        methodName = lastFrame.GetMethod().Name; 
 
    return methodName; 
}