Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 2686
感情败类
感情败类 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:47

    I resolved in This Way (it's a little bit laboriouse, but it's surely the faster in runtime).

    In VB (sorry, but I think it's not hard translate it in C#), I make this substitution with RE:

    (?<(.*ComponentModel\.)Bindable\(True\)>)( |\r\n)*(?(Public|Private|Friend|Protected) .*Property )(?[^ ]*) As (?.*?)[ |\r\n](?![ |\r\n]*Get)
    

    with:

    Private _${Name} As ${Type}\r\n${Attr}\r\n${Def}${Name} As ${Type}\r\nGet\r\nReturn _${Name}\r\nEnd Get\r\nSet (Value As ${Type})\r\nIf _${Name} <> Value Then \r\n_${Name} = Value\r\nRaiseEvent PropertyChanged(Me, New ComponentModel.PropertyChangedEventArgs("${Name}"))\r\nEnd If\r\nEnd Set\r\nEnd Property\r\n
    

    This transofrm all code like this:

    
    Protected Friend Property StartDate As DateTime?
    

    In

    Private _StartDate As DateTime?
    
    Protected Friend Property StartDate As DateTime?
        Get
            Return _StartDate
        End Get
        Set(Value As DateTime?)
            If _StartDate <> Value Then
                _StartDate = Value
                RaiseEvent PropertyChange(Me, New ComponentModel.PropertyChangedEventArgs("StartDate"))
            End If
        End Set
    End Property
    

    And If I want to have a more readable code, I can be the opposite just making the following substitution:

    Private _(?.*) As (?.*)[\r\n ]*(?<(.*ComponentModel\.)Bindable\(True\)>)[\r\n ]*(?(Public|Private|Friend|Protected) .*Property )\k As \k[\r\n ]*Get[\r\n ]*Return _\k[\r\n ]*End Get[\r\n ]*Set\(Value As \k\)[\r\n ]*If _\k <> Value Then[\r\n ]*_\k = Value[\r\n ]*RaiseEvent PropertyChanged\(Me, New (.*ComponentModel\.)PropertyChangedEventArgs\("\k"\)\)[\r\n ]*End If[\r\n ]*End Set[\r\n ]*End Property
    

    With

    ${Attr} ${Def} ${Name} As ${Type}
    

    I throw to replace the IL code of the set method, but I can't write a lot of compiled code in IL... If a day I write it, I'll say you!

提交回复
热议问题