获取C#中当前正在执行的函数的名称? [英] Get the name of the currently executing function in C# ?

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

问题描述

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

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

推荐答案

在什么情况下?您可能正在使用该函数,因此,除非您尝试编写某种宏,否则我不知道如何找到该函数.在这种情况下,答案是否定的.您不能在C#中编写与C ++查找当前行号相同的宏,等等.
In what context ? You''d be IN the function in question, so, I don''t see how you''d need to find that out, unless you''re trying to write some sort of macro. In that case, the answer is no, you can''t write macros in C# that would work the way C++ did to find the current line number, etc.



这是我的一部分在类似情况下用于日志记录组件中,尽管我认为它要求存在pdb文件.它不会像您所做的那样追溯异常,但这是检测代码的好方法.
This is part of something I used in a logging component in a similar situation, although I believe it requires the pdb file to be present. It doesn''t trace back the exception like you''re doing, but it is a nice way to instrument the code.
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#中当前正在执行的函数的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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