從.Net 4.5開始提供了CallerMemberName這個Attribute可以獲得調用方法的成員名稱,這個用來實現數據綁定中簡化實現INotifyPropertyChanged接口很有幫助。
但是在.Net 4.0及之前是不支持的,可以使用StackTrace達到同樣的目的:
new StackTrace(true).GetFrame(1).GetMethod().Name
就可以獲得調用當前方法的方法名。
原理就是StackTrace類獲得的是當前的調用堆棧,堆棧中第0個是當前方法,堆棧中第1個方法就是調用當前方法的方法。
如果想獲得屬性名,則通過下面的方法來從get_Id這樣的方法名中取出屬性名:
private static string GetProperyName(string methodName)
{
if (methodName.StartsWith("get_") || methodName.StartsWith("set_") ||
methodName.StartsWith("put_"))
{
return methodName.Substring("get_".Length);
}
throw new Exception(methodName+" not a method of Property");
}
下面就是兼容舊版本.Net的BindableBase:
class BindableBase:INotifyPropertyChanged
{
private Dictionary<string, object> dict = new Dictionary<string, object>();
private static string GetProperyName(string methodName)
{
if (methodName.StartsWith("get_") || methodName.StartsWith("set_") ||
methodName.StartsWith("put_"))
{
return methodName.Substring("get_".Length);
}
throw new Exception(methodName+" not a method of Property");
}
protected void SetValue(object value)
{
string propertyName = GetProperyName(new StackTrace(true).GetFrame(1).GetMethod().Name);
dict[propertyName] = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected object GetValue()
{
string propertyName = GetProperyName(new StackTrace(true).GetFrame(1).GetMethod().Name);
if (dict.ContainsKey(propertyName))
{
return dict[propertyName];
}
else
{
return null;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
當然這個方式使用的是StackTrace,性能略低於CallerMemberName。
如鵬網.Net培訓班正在報名,有網絡的地方就可以參加如鵬網的學習,學完就能高薪就業,點擊此處了解
三年前只要懂“三層架構”就可以說“精通分層架構”;現在則需要懂IOC(AutoFac等)、CodeFirst、lambda、DTO等才值錢;
三年前只要會SQLServer就可以說自己“精通數據庫開發”;現在則需還需要掌握MySQL等開源數據庫才能說是“.Net開源”時代的程序員;
三年前只要會進行用戶上傳內容的安全性處理即可;現在則需要熟悉雲存儲、CDN等才能在雲計算時代游刃有余;
三年前只要掌握Lucene.Net就會說自己“熟悉站內搜索引擎開發”;現在大家都用ElasticSearch了,你還用Lucene.Net就太老土了;
三年前發郵件還是用SmtpClient;現在做大型網站發郵件必須用雲郵件引擎;
三年前緩存就是Context.Cache;現在則是Redis、Memcached的天下;
如鵬網再次引領.Net社區技術潮流!點擊此處了解如鵬網.Net最新課程