Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 2469
感情败类
感情败类 2020-11-21 05:23

Microsoft should have implemented something snappy for INotifyPropertyChanged, like in the automatic properties, just specify {get; set; notify;} I

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 05:40

    I haven't actually had a chance to try this myself yet, but next time I'm setting up a project with a big requirement for INotifyPropertyChanged I'm intending on writing a Postsharp attribute that will inject the code at compile time. Something like:

    [NotifiesChange]
    public string FirstName { get; set; }
    

    Will become:

    private string _firstName;
    
    public string FirstName
    {
       get { return _firstname; }
       set
       {
          if (_firstname != value)
          {
              _firstname = value;
              OnPropertyChanged("FirstName")
          }
       }
    }
    

    I'm not sure if this will work in practice and I need to sit down and try it out, but I don't see why not. I may need to make it accept some parameters for situations where more than one OnPropertyChanged needs to be triggered (if, for example, I had a FullName property in the class above)

    Currently I'm using a custom template in Resharper, but even with that I'm getting fed up of all my properties being so long.


    Ah, a quick Google search (which I should have done before I wrote this) shows that at least one person has done something like this before here. Not exactly what I had in mind, but close enough to show that the theory is good.

提交回复
热议问题