从.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最新课程