Using string constant for notify property changed

前端 未结 4 1399
-上瘾入骨i
-上瘾入骨i 2021-01-15 13:49

I am working with some existing code and trying to figure out the advantage (if any) of using a string constant for the name of a property when implementing INotifyPropertyC

4条回答
  •  长情又很酷
    2021-01-15 14:17

    Both versions are equally prone to typing errors.

    If you have a somewhat recent version of .NET, your property changed handler should look like this:

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      var handler = this.PropertyChanged;
      if (handler != null)
      {
        handler(this, new PropertyChangedEventArgs(propertyName));
      }
    }
    

    Then your property looks like this:

    private int _customerId;
    public int CustomerId
    {
        get
        {
             return _customerId;
        }
        set
        {
             if (_cusomterId != value)
             {
                  _customerId = value;
                  this.OnPropertyChanged();
             }
        }
    }
    

    And you don't have any trouble with typing errors.

提交回复
热议问题