2013-08-06 58 views
1

這是非常簡單的獲得方法調用者,甚至通過使用編譯器服務中獲得的屬性名稱的變化,如:Get方法調用者FOM集「功能」

public class EmployeeVM:INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

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

    private string _name; 

    public string Name 
    { 
     get { return _name; } 
     set 
     { 
      _name = value; 
      // The compiler converts the above line to: 
      // RaisePropertyChanged ("Name"); 
     } 
    } 

    private string _phone; 

    public string Phone 
    { 
     get { return _phone; } 
     set 
     { 
      _phone = value; 
      OnPropertyChanged(); 
     // The compiler converts the above line to: 
      // RaisePropertyChanged ("Phone"); 
     } 
    } 
} 

但有可能得到來自set內部的「set」函數的調用者?我不知道你是如何在該範圍內進行語法定義的。 AKA,誰打電話=?

+0

C#5添加了來電信息。 http://blogs.msdn.com/b/mvpawardprogram/archive/2012/03/26/introduction-of-new-features-in-c-5-0.aspx – lukegravitt

回答

2

看看StackFrame,特別是GetMethod,它給了你方法名(你需要選擇一個以前的堆棧幀,具體取決於是否寫入幫助函數)。從本文的示例:

  StackTrace st = new StackTrace(); 
      StackTrace st1 = new StackTrace(new StackFrame(true)); 
      Console.WriteLine(" Stack trace for Main: {0}", 
       st1.ToString()); 
      Console.WriteLine(st.ToString()); 

有跡象表明,可以通過像How do I find the type of the object instance of the caller of the current function?

1

不幸的是[CallerMemberName] AttributeUsage設置爲AttributeTargets.Parameter搜索的StackFrame找到其他類似的問題,所以它只能用於參數,如在方法簽名

但是你可以使用StackFrameAlexei Levenkov提到

public string Phone 
{ 
    get { return _phone; } 
    set 
    { 
     string setterCallerName = new StackFrame(1).GetMethod().Name; 

     _phone = value; 
     OnPropertyChanged(); 
    } 
}