得到當前正在啟動並執行方法或屬性名稱[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]