ASP.NET中實現擷取調用方法名

來源:互聯網
上載者:User

   需要添加相應的命名空間:

  複製代碼 代碼如下:

  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 查看。

  使用反射可以遍曆獲得類的所有屬性名稱,方法名,成員名,其中一個有趣的小例子:通過反射將變數值轉為變數名本身。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.