• 爱情文章
  • 亲情文章
  • 友情文章
  • 生活随笔
  • 校园文章
  • 经典文章
  • 人生哲理
  • 励志文章
  • 搞笑文章
  • 心情日记
  • 英语文章
  • 范文大全
  • 作文大全
  • 新闻阅读
  • 当前位置: 山茶花美文网 > 生活随笔 > 正文

    【ASP.NET中实现获取调用方法名】 获取NET

    时间:2020-05-26来源:山茶花美文网 本文已影响 山茶花美文网手机站

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

    复制代码 代码如下:

    using System;

    using System.Diagnostics;

    using System.Reflection;

    如果仅是获取当前方法名,可以使用如下代码:

    复制代码 代码如下:

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

    }

    但一般情况下是获取此记录日志方法的调用方,因此需要使用下面的代码:(此方法仅为演示)

    代码如下:

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

    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程序的执行顺序:

    代码如下:

    System.Threading.ThreadHelper.ThreadStart()

    System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

    Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

    System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)

    然后进入方法Main中。

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

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

    • 【ASP.NET中实现获取调用方法名】 获取NET 相关文章:
    • 爱情文章
    • 亲情文章
    • 友情文章
    • 随笔
    • 哲理
    • 励志
    • 范文大全