如何找到的方法调用C#的全名全名、方法

2023-09-03 12:27:35 作者:-少年多梦不多情、

我如何才能找到在C#中调用方法的全名。我已经看到了解决方案:

How can I find the full name of a calling method in c#. I have seen solutions:

我怎样才能在C#中的调用方法

How我能找到调用当前方法的方法?

Get从调用的函数在C#中调用函数名

但他们只给我的最高水平。请看例子:

But they only give me the top level. Consider the example:

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

这只是输出'主'我怎样才能得到它打印Sandbox.Program.Main?

This simply outputs 'Main' How can I get it to print 'Sandbox.Program.Main'?

在任何人开始问我为什么需要使用此,它的一个简单的日志框架是我的工作。

Before anyone starts asking why I need to use this, its for a simple logging framework that I am working on.

修改

添加到Matzi的回答是:

Adding onto Matzi's Answer:

下面是解决方案:

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像它应该

Produces 'Sandbox.Program.Main' like it should

推荐答案

这是像here.

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

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