2012-04-20 32 views
11

有在NotificationObject該方法的一個過載: -RaisePropertyChanged <T>如何找到屬性名稱?

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

我們寫以下列方式中的屬性的setter:

RaisePropertyChanged(() => PropertyVariable); 

它是如何工作的?它如何從這個Lambda表達式中找到屬性名稱?

+0

這說明它如何做到:http://stackoverflow.com/questions/141370/inotifypropertychanged-property-name-hardcode- vs-reflection – Henrik 2012-04-20 09:15:35

+1

在C#5中,你甚至不需要反射魔法:http://www.robfe.com/2011/09/raising-the-right-propertychanged-with-c-5s-caller-info -attributes/ – Vlad 2012-04-20 09:17:24

+0

我忍不住在這裏提示resharper,當你嘗試去方法定義(F12)時,它很容易反編譯。您也可以像反射器一樣使用其他反編譯器。 – mkb 2015-09-21 12:18:37

回答

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); 
} 
相關問題