取當前方法或函式的名稱

此篇文章引用自
  • Get Caller Name
[.NET]CallerMemberNameAttribute-可讓您取得方法呼叫端的方法或屬性名稱

引言

C#不像C++中有一些預先定義的巨集(Predefined Marcors)可以使用
例如常用在輸出Trace Log的:
 __FUNCTION__ - 目前原始程式檔名稱
 __LINE__ - 目前原始程式檔中行號
在C#當中就沒有提供 (註: .NET中有提供 MethodBase.GetCurrentMethod可以Runtime取得函式名)

解法一: System.Runtime.CompilerServices

從.NET 4.5起在System.Runtime.CompilerServices 有提供一些類似的功能
CallerFilePathAttribute - 取得呼叫端的程式檔名稱
CallerMemberNameAttribute - 取得呼叫端的函式名稱
CallerLineNumberAttribute - 取得呼叫端的程式檔中的行號

只要在Method中設定CallerMemberNameAttribute(要using System.Runtime.CompilerServices;),就可以在Method中取得呼叫端資訊,如下為MSDN的範例,

//using System.Runtime.CompilerServices;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TraceMessage("Hi, Rainmaker!");
        }

        public static void TraceMessage(string message,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
        {
            Console.WriteLine("message: " + message);
            Console.WriteLine("member name: " + memberName);
            Console.WriteLine("source file path: " + sourceFilePath);
            Console.WriteLine("source line number: " + sourceLineNumber);
        }
    }
}
Get Current Method Name


[MethodImpl(MethodImplOptions.NoInlining)]
private string _CurrentMethodName([CallerMemberName] string memberName = "")
{
    return memberName;
}

解法二: System.Reflection.MethodBase

System.Reflection.MethodBase.GetCurrentMethod();
System.Reflection.MethodInfo.GetCurrentMethod();
string methodName = MethodInfo.GetCurrentMethod().ToString();


解法三: System.Diagnostics.StackTrace

StackTrace st = new StackTrace ();
StackFrame sf = st.GetFrame (0);
MethodBase currentMethodName = sf.GetMethod ();
Or, if you'd like to have a helper method:
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentMethod ()
{
    StackTrace st = new StackTrace ();
    StackFrame sf = st.GetFrame (1);

    return sf.GetMethod().Name;
}

https://dotblogs.com.tw/h20/2017/12/05/121148
https://dotblogs.com.tw/larrynung/archive/2009/02/28/7318.aspx
http://hant.ask.helplib.com/r/post_213881


留言

這個網誌中的熱門文章

嘗試卸載資料庫時,發生資料庫正在使用的而無法卸載的可能解決方案

ASP.NET常用的RegularExpressionValidator驗證

PMP常用的英文單字