c# - 如何在 C# 中查找调用方法的全名

标签 c# .net reflection

如何在 C# 中找到调用方法的全名?我看到了解决方案:

How I can get the calling methods in C#

How can I find the method that called the current method?

Get Calling function name from Called function

但他们只给我顶级。考虑这个例子:

namespace Sandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            test();
        }

        static void test()
        {
            var stackTrace = new StackTrace();
            var methodBase = stackTrace.GetFrame(1).GetMethod();
            Console.WriteLine(methodBase.Name);
        }
    }
}

这只是输出“Main”。如何让它打印“Sandbox.Program.Main”?

这是我正在开发的一个简单的日志记录框架。


添加到 Matzi 的回答中:

解决方法如下:

namespace Sandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            test();
        }

        static void test()
        {
            var stackTrace = new StackTrace();
            var methodBase = stackTrace.GetFrame(1).GetMethod();
            var Class = methodBase.ReflectedType;
            var Namespace = Class.Namespace;         // Added finding the namespace
            Console.WriteLine(Namespace + "." + Class.Name + "." + methodBase.Name);
        }
    }
}

它会像它应该的那样生成“Sandbox.Program.Main”。

最佳答案

这类似于 here .

MethodBase method = stackTrace.GetFrame(1).GetMethod();
string methodName = method.Name;
string className = method.ReflectedType.Name;

Console.WriteLine(className + "." + methodName);

关于c# - 如何在 C# 中查找调用方法的全名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367830/

相关文章:

c# - 可排序、可拖动、可排序表 + mvc 未正确更新顺序

c# - 我如何以编程方式知道代码在哪个平台下运行?

java 反射列表 NoSuchMethodException

go - 如何获取类型的字符串表示形式?

c# - 带有sql查询的字符串变量被框架改变了

c# - URL 的编码参数

c# - 使用 HangFire 的正确架构

c# - 如何解决 C# .NET N 层应用程序中的乐观并发更新?

.net - Internet Explorer 保护模式错误

java - 运行时签名是什么?