如何在 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/