NotificationObject
中有一个此方法的重载: -
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression);
我们在以下方式写入属性的设置者:
RaisePropertyChanged(() => PropertyVariable);
它是如何运作的?它如何从这个Lambda表达式中找到属性名称?
答案 0 :(得分:15)
Expression<TDelegate>
表示lambda表达式的抽象语法树。因此,您只需分析此语法树以找到属性名称:
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
var memberExpr = propertyExpression.Body as MemberExpression;
if (memberExpr == null)
throw new ArgumentException("propertyExpression should represent access to a member");
string memberName = memberExpr.Member.Name;
RaisePropertyChanged(memberName);
}