得到當前正在啟動並執行方法或屬性名稱[C#]

來源:互聯網
上載者:User
得到當前正在啟動並執行方法或屬性名稱[C#]  

2012-04-18 22:50:08|  分類: C#|字型大小 訂閱

  

     C/C++在編譯時間有個__FUNCTION__宏可以擷取當前的方法名,而C#中並沒有這樣的預先處理宏,無法在編譯時間獲得函數名資訊。但C#中卻可以通過反射來在運行時拿到這些資訊。MethodBase.GetCurrentMethod().Name就是一個很好的渠道; 而通過指定可忽略的棧深度new StackFrame(0).GetMethod().Name提供了更大的靈活性。    以上方法在可以方便得到普通函數的名稱,但將其用於屬性(Property)時,會得到get_Property或set_Property這樣被修飾過的名字。如果我們要得到代碼中的屬性名稱,需要將簽名的get_和set_修飾去掉。當然不能簡單的進行Substring(4),否則就無法和使用者定義的get_UserMethod方法區分。這是個問題...

public static string GetMethodName()
{
         var method = new StackFrame(1).GetMethod(); // 這裡忽略1層堆棧,也就忽略了當前方法GetMethodName,這樣拿到的就正好是外部調用GetMethodName的方法資訊
         var property = (
                   from p in method.DeclaringType.GetProperties(
                            BindingFlags.Instance |
                            BindingFlags.Static |
                            BindingFlags.Public |
                            BindingFlags.NonPublic)
                   where p.GetGetMethod(true) == method || p.GetSetMethod(true) == method
                   select p).FirstOrDefault();
         return property == null ? method.Name : property.Name;
}

    以上通過將當前MethodInfo和調用者類型中所有的PropertyInfo對應的get或set的MethodInfo進行比對,以鑒別調用者是屬性,然後再相應的返回屬性名稱或方法名。  參考:how to get current property name and current class name?2013-1-25

    C# 4.5開始,可以採用 CallerMemberName特性來獲得調用屬性或方法的名稱。如此實現INotifyPropertyChanged就簡捷多了:

publiceventPropertyChangedEventHandlerPropertyChanged;

// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
privatevoidNotifyPropertyChanged([CallerMemberName]stringpropertyName ="")
{
if(PropertyChanged!=null)
{
PropertyChanged(this,newPropertyChangedEventArgs(propertyName));
}
}

    參考: C# 5–Making INotifyPropertyChanged Easier2013-1-26

    By using Caller Info attributes, you can obtain information about the caller to a method. You can obtain file path of the source code, the line number in the source code, and the member name of the caller. This information is helpful for tracing, debugging, and creating diagnostic tools.[MSDN]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.