程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 轉:.NET獲取當前方法名或調用此方法的方法名

轉:.NET獲取當前方法名或調用此方法的方法名

編輯:C#入門知識

Introduction

Before .NET, we were always looking for a way to log current method name in a log file for better logging. But, there were no functionalities that could have helped in this, and it was left as an uncompleted job.

But, with .NET, we could easily find out the name of the current method or parent method. This has been accomplished by StackFrame, StackTrace, and MethodBase classes in System.Diagnostics and System.Reflection namespaces.

  • StackFrame provides information about function call on stack call for current process.
  • StackTrace is a collection of StackFrame.
  • MethodBase is an abstract class containing information about current method.

Note: When an exception occurs in the method, exception object contains a reference to the StackTrace object that could be used to log the method name. But for logging a method name without an error generated, we need to read it from the stack, using StackFrame class.

In the sample, MethodBase object would reference to current function on stack call returned by StackFrame object. To get the parent method, we would use StackTrace to get parent’s StackFrame object.

Create a new console application:

Add namespaces:

using System.Diagnostics; using System.Reflection;

Create a new static function named WhatsMyName and call it from the Main function.

[STAThread] static void Main(string[] args) { WhatsMyName(); } // function to display its name private static void WhatsMyName() { stackFrame = new (); MethodBase methodBase = stackFrame.GetMethod(); Console.WriteLine(methodBase.Name ); // Displays “WhatsmyName” WhoCalledMe(); } // Function to display parent function private static void WhoCalledMe() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); // Displays “WhatsmyName” Console.WriteLine( " Parent Method Name {0} ", methodBase.Name ); }

Note: This feature is not available in .NET Compact Framework as StackFrame class is unavailable. For that, you would need to use same old method of manually passing method name to the logging function.

http://www.codeproject.com/Articles/7964/Logging-method-name-in-NET

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved