12

此方法有一个重载NotificationObject:-

protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression);

我们在property的setter中这样写:

RaisePropertyChanged(() => PropertyVariable);

它是如何工作的?它如何从这个 Lambda 表达式中找到属性名称?

4

1 回答 1

16

AnExpression<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);
}
于 2012-04-20T09:15:57.873 回答