網頁

2012年11月8日星期四

C# 5.0新功能 - Caller Information Attributes

PHP語言中,有樣東西叫Magic Constants,即大家常見的"__LINE__","__FILE__"等等。

這亦是我渴望在C#出現的東西,因為這對Debug或者是Logging都很有用。

C# 5.0就剛巧新增這個功能,叫做Caller Information,介紹一下。

取錄自MSDN,Caller Information有三個主要Attribute,分別為 :
  • CallerFilePathAttribute
    • Full path of the source file
  • CallerLineNumberAttribute
    • Line number in the source file at which the method is called.
  • CallerMemberNameAttribute
    • Method or property name

使用方法很簡單,只需把Attribute放置在Optional Parameters前端,就如一般的Class Attribute一樣。
以下面程式碼為例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.CompilerServices;

namespace WhoCallMyFunction
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Comment lines will not affect the LineNumber.
            MyFunction(" I Know That Feel Bro.");
        }

        private void MyFunction( string WhyCallMe,
                [CallerMemberName] string MemberName = "",
                [CallerFilePath] string FilePath = "",
                [CallerLineNumber] int LineNumber = 0
            )
        {
            Console.WriteLine("\r\n WhyCallMe : {0} \r\n " + 
                                       "Time : {1} \r\n " + 
                                       "Member name : {2} \r\n "+
                                       "FilePath : {3} \r\n "+
                                       "LineNumber : {4} ", 
                                       WhyCallMe, DateTime.Now.ToString(), MemberName, FilePath, LineNumber.ToString());
        }
    }
}

最後便會輸出
WhyCallMe :  I Know That Feel Bro. 
 Time : 8/11/2012 15:21:32 
 Member name : Form1_Load 
 FilePath : c:\Users\Ming\Documents\Visual Studio 2012\Projects\WhoCallMyFunction\WhoCallMyFunction\Form1.cs 
 LineNumber : 20 

雖然這是C# 5.0的新功能,但原來有方法可以令舊版本都支援。
詳細請見:
Using C# 5 caller info attributes when targeting earlier versions of the .NET framework
Calling C# 4/3/2.... Using the new C# 5 Caller Information with C# 2,3,4...

沒有留言:

發佈留言