获取最后调用的方法的名称 [英] Get name of last called method

查看:109
本文介绍了获取最后调用的方法的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  public partial class Form1:Form 
{
public Form1 ()
{
InitializeComponent();
try
{
this.CheckValue(true); //调用方法
}
catch(Exception ex)
{
//如何获取最后调用方法的名称
}
}

public int CheckValue(bool sender)
{
var qwe = int.Parse(qwe); // invoke a exception

return 0;
}
}



我需要在catch block最后调用的方法(在这种情况下是CheckValue),但它返回称为方法是StringToNumber。



我尝试使用StackTrace获取它:

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

这可以吗?

解决方案

简答:



是的,你可以!!! b
$ b




我只是想使用扩展方法和诀窍在这里,是获得所需的类的最后一帧,否则会得到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;
}


I have the following code:

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;
    }
}

I need to get in "catch block" name of last called method (in this case "CheckValue"), but it return that called method is "StringToNumber".

I try to get it using StackTrace:

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

It's possible to do this?

解决方案

Short Answer:

Yes, You can!!!


I'd just play around with Extension Methods and the trick here, is to get the last frame of the desired class, otherwise it would get methods of mscorlib assembly. So here it go:

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;
}

这篇关于获取最后调用的方法的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆