本文介绍了获取C#中当前正在执行的函数的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在C#中获取当前正在执行的函数的名称?

Is there a way to get the name of the currently executing function in C#?

推荐答案



public static void DebugWriteTrace()
{
    System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
    string f1info, f2info;
    GetTraceInfo(trace, out f1info, out f2info);
    Write(0, f1info + f2info);
}
private static void GetTraceInfo(StackTrace trace, out string f1, out string f2)
{
    System.Diagnostics.StackFrame sf = trace.GetFrame(1); //Gets caller's info
    int lineNo = sf.GetFileLineNumber();
    f1 = System.IO.Path.GetFileNameWithoutExtension(sf.GetFileName())
        + ":" + sf.GetMethod().Name
        + ((lineNo != 0) ? ", Ln " + lineNo.ToString() : "");
    f2 = string.Empty;
    if (trace.FrameCount > 2)
    {
        sf = trace.GetFrame(2);
        lineNo = sf.GetFileLineNumber();
        f2 = "; called from " + sf.GetMethod().Name
            + ((lineNo != 0) ? ", Ln " + lineNo.ToString() : "");
    }
}


DebugWriteTrace会有重载,这就是为什么GetTraceInfo 是分开的并返回两个字符串而不是一个字符串的原因.


There were overloads for the DebugWriteTrace, which is why GetTraceInfo is separate and returns two strings instead of one.


这篇关于获取C#中当前正在执行的函数的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 02:18