.NET 中获取调用方法名

  在写记录日志功能时,需要记录日志调用方所在的模块名、命名空间名、类名以及方法名,想到使用的是反射(涉及到反射请注意性能),但具体是哪一块儿还不了解,于是搜索,整理如下:

需要添加相应的命名空间:

using System;
using System.Diagnostics;
using System.Reflection;

如果仅是获取当前方法名使用 MethodBase.GetCurrentMethod 方法(返回表示当前正在执行的方法的 MethodBase 对象),可以使用如下代码:

复制代码
public static void WriteSysLog(int level, string content)
{
    MethodBase mb = MethodBase.GetCurrentMethod();
    string systemModule = Environment.NewLine;
    systemModule += "模块名:" + mb.Module.ToString() + Environment.NewLine;
    systemModule += "命名空间名:" + mb.ReflectedType.Namespace + Environment.NewLine;
    //完全限定名,包括命名空间
    systemModule += "类名:" + mb.ReflectedType.FullName + Environment.NewLine;
    systemModule += "方法名:" + mb.Name;

    Console.WriteLine("LogDate: {0}{1}Level: {2}{1}systemModule: {3}{1}content: {4}", DateTime.Now, Environment.NewLine, level, systemModule, content);
    Console.WriteLine();
}
复制代码

本文地址:http://www.cnblogs.com/Interkey/p/GetMethodName.html
但一般情况下是获取此记录日志方法的调用方,因此需要使用下面的代码:(此方法仅为演示)

复制代码
public static void WriteSysLog(string content)
{
    const int level = 1000;

    StackTrace ss = new StackTrace(true);
    //index:0为本身的方法;1为调用方法;2为其上上层,依次类推
    MethodBase mb = ss.GetFrame(1).GetMethod();

    //本文地址:http://www.cnblogs.com/Interkey/p/GetMethodName.html
    StackFrame[] sfs = ss.GetFrames();
    string systemModule = Environment.NewLine;
    systemModule += "模块名:" + mb.Module.ToString() + Environment.NewLine;
    systemModule += "命名空间名:" + mb.DeclaringType.Namespace + Environment.NewLine;
    //仅有类名
    systemModule += "类名:" + mb.DeclaringType.Name + Environment.NewLine;
    systemModule += "方法名:" + mb.Name;

    Console.WriteLine("LogDate: {0}{1}Level: {2}{1}systemModule: {3}{1}content: {4}", DateTime.Now, Environment.NewLine, level, systemModule, content);
    Console.WriteLine();
}
复制代码

对于这一点儿,感觉有意思的是Main的调用方,System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)。

通过

StackTrace ss = new StackTrace(true);
StackFrame[] sfs = ss.GetFrames();

可以得知.NET程序的执行顺序:

  1. System.Threading.ThreadHelper.ThreadStart()
  2. System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  3. Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  4. System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)

然后进入方法Main中。 

 
  StackFrame指的是一个.net运行的时候堆栈上的一个帧(Frame),每次进入一个方法的时候就会有一个新的方法帧压入线程执行堆栈,可以通过StackFrame获取相关的信息,比如当前代码所在文件名和行号。
  拓展方法是在.NET Framework 3.5以上版本才支持的,需要组件System.Core。

相关类:

  1. 在System.Diagnostics 命名空间中的 StackTrace 类 ,表示一个堆栈跟踪,它是一个或多个堆栈帧的有序集合。
  2. 在System.Diagnostics 命名空间中的 StackFrame 类 ,提供关于 StackFrame(表示当前线程的调用堆栈中的一个函数调用)的信息。
  3. 在System.Reflection 命名空间中的 MethodBase 类 ,提供有关方法和构造函数的信息。

另外,从 MethodBase 类 还可以获取很多其他属性,可以自行定位到System.Reflection.MethodBase 查看。

使用反射可以遍历获得类的所有属性名,方法名,成员名,其中一个有趣的小例子:通过反射将变量值转为变量名本身 

文件:GetCurrentMethodName.zip [VS版本为2013,本例仅为演示]


后续:

感谢博友的提醒,使用CallerMemberNameAttribute 也可以实现获取调用方法名。示例请参考:调用方信息(C# 和 Visual Basic)

C# 5.0 给我们带来了三个非常有用的编译器特性:CallerMemberNameAttributeCallerFilePathAttributeCallerLineNumberAttribute (在System.Runtime.CompilerServices 命名空间中),但这三个Attribute 是定义.NET Framework 4.5里的。

 

如果在低于.NET4.5中使用需要定义这些特性:

复制代码
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerMemberNameAttribute : Attribute { }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerFilePathAttribute : Attribute { }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerLineNumberAttribute : Attribute { }
}
复制代码

关于 Attribute 和 AttributeUsageAttribute 的使用可自行搜索,有些偏题了…


 

参考:

  1. Logging method name in .NET
  2. c# 获取命名空间 类名 方法名
  3. 得到当前正在运行的方法或属性名[C#] 
  4. C#如何获取被调用的方法的名称及参数列表?
  5. 获得当前程序的 空间名.类名.方法名
  6. C#获得调用方法的名称和类名
  7. 浅析StackTrace
  8. C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用

posted on   Cosmic_Spy  阅读(7678)  评论(12编辑  收藏  举报

编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Your IP:
点击右上角即可分享
微信分享提示

返回顶部