RaisePropertyChanged <t>如何找到属性名称?</t>

时间:2012-04-20 09:11:55

标签: .net c#-4.0 lambda

NotificationObject中有一个此方法的重载: -

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

我们在以下方式写入属性的设置者:

RaisePropertyChanged(() => PropertyVariable);

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

1 个答案:

答案 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);
}