当登录c#时,我如何才能知道调用当前方法的方法的名称?我知道所有关于System.Reflection.MethodBase.GetCurrentMethod(),但我想在堆栈跟踪中走一步。我考虑过解析堆栈跟踪,但我希望找到一种更清晰、更显式的方式,比如Assembly.GetCallingAssembly(),但用于方法。


当前回答

通常,您可以使用System.Diagnostics. stacktrace类来获取System.Diagnostics。然后使用GetMethod()方法获取System.Reflection.MethodBase对象。然而,这种方法有一些注意事项:

它表示运行时堆栈——优化可以内联一个方法,并且您不会在堆栈跟踪中看到该方法。 它不会显示任何本机帧,所以即使有机会您的方法被本机方法调用,这也将不起作用,而且实际上目前没有可用的方法来做到这一点。

(注:我只是在扩展Firas Assad提供的答案。)

其他回答

我们也可以用来找到调用者。

假设你有一个你定义的方法:

public void MethodA()
    {
        /*
         * Method code here
         */
    }

你想找到它的调用者。

1. 改变方法签名,这样我们就有了一个Action类型的参数(Func也可以):

public void MethodA(Action helperAction)
        {
            /*
             * Method code here
             */
        }

2. Lambda名称不是随机生成的。规则似乎是:> <CallerMethodName>__X 其中CallerMethodName被前面的函数替换,X是一个索引。

private MethodInfo GetCallingMethodInfo(string funcName)
    {
        return GetType().GetMethod(
              funcName.Substring(1,
                                funcName.IndexOf("&gt;", 1, StringComparison.Ordinal) - 1)
              );
    }

3.当我们调用MethodA时,Action/Func参数必须由调用方方法生成。 例子:

MethodA(() => {});

4. 在MethodA内部,我们现在可以调用上面定义的helper函数,并找到调用方方法的MethodInfo。

例子:

MethodInfo callingMethodInfo = GetCallingMethodInfo(serverCall.Method.Name);

也许你正在寻找这样的东西:

StackFrame frame = new StackFrame(1);
frame.GetMethod().Name; //Gets the current method name

MethodBase method = frame.GetMethod();
method.DeclaringType.Name //Gets the current class name
StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(1);
string methodName = caller.GetMethod().Name;

我想这就够了。

试试这个:

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调用方法使用反射[c#]。

要获得方法名和类名,请尝试以下方法:

    public static void Call()
    {
        StackTrace stackTrace = new StackTrace();

        var methodName = stackTrace.GetFrame(1).GetMethod();
        var className = methodName.DeclaringType.Name.ToString();

        Console.WriteLine(methodName.Name + "*****" + className );
    }