INotifyPropertyChanged property name - hardcode vs reflection?

前端 未结 16 1569
感动是毒
感动是毒 2020-11-28 05:13

What is the best way to specify a property name when using INotifyPropertyChanged?

Most examples hardcode the property name as an argument on the PropertyChanged E

16条回答
  •  感情败类
    2020-11-28 05:42

    Roman:

    I'd say you wouldn't even need the "Person" parameter - accordingly, a completely generic snippet like the one below should do:

    private int age;
    public int Age
    {
      get { return age; }
      set
      {
        age = value;
        OnPropertyChanged(() => Age);
      }
    }
    
    
    private void OnPropertyChanged(Expression> exp)
    {
      //the cast will always succeed
      MemberExpression memberExpression = (MemberExpression) exp.Body;
      string propertyName = memberExpression.Member.Name;
    
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }
    

    ...however, I prefer sticking to string parameters with conditional validation in Debug builds. Josh Smith posted a nice sample on this:

    A base class which implements INotifyPropertyChanged

    Cheers :) Philipp

提交回复
热议问题