[C#.NET] 使用 Caller Info 實現 TarceSource 的追蹤功能

  • 2337
  • 0
  • C#
  • 2016-03-24

[C#.NET] 使用 Caller Info 實現類似 TarceSource 的追蹤功能

以往我們會利用 StackTrace,來取得目前方法被哪個方法調用,請參考 [C#.NET] 追蹤類別–StackTrace

 

在 .NET 4.5 提供了以下這三個 Attribute 類別,也能達到 StackTrace 的效果

https://msdn.microsoft.com/zh-tw/library/hh534540.aspx

CallerFilePathAttribute 類別

CallerLineNumberAttribute 類別

CallerMemberNameAttribute 類別

 

Caller Info 可見範圍只能在參數



 

使用方式很簡單

        public void RunTest()
        {
            Run();
        }

        private void Run(
            [CallerMemberName] string memberName = null,
            [CallerFilePath] string filePath = null,
            [CallerLineNumber]int lineNumber = -1)
        {
            Console.WriteLine(@"CallerMemberName:{0}
CallerFilePath:{1}
CallerLineNumber:{2}",
                memberName, filePath, lineNumber);
        }

 

還有另外 INotifyPropertyChanged 情境可以使用,以往屬性變動時必須要調用 OnPropertyChanged,這必須傳字串過去,當然你也可以用 StackTrace ;字串是弱型別,打錯了也不知道,StackTrace 似乎是一個比較安全的做法

image

 

現在,參數加上 CallerMemberName 就簡單多了,

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

 

不需要再敲欄位名稱了

image

 

同場加映:

個人在實作 DTO 的時候預設會用自動屬性(輸入 prop tab),裝了 Resharper 後,在 OnPropertyChanged 加上 [NotifyPropertyChangedInvocator] ,然後編輯游標停在屬性上,鐵鎚圖型按下去,跳出一個選單項目叫"To property with change notification"

image

 

按下去,它會自動幫我加上通知邏輯,處理完整屬性又變得更方便一些些

image

 

畫面如下:

Untitled


本文出自:http://www.dotblogs.com.tw/yc421206/archive/2015/03/27/150858.aspx

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo