INotifyPropertyChanging 和验证:何时引发 PropertyChanging?
INotifyPropertyChanged 是相当不言自明的,我想我很清楚何时提出该问题(即当我完成更新值时)。
如果我实现 INotifyPropertyChanging,我倾向于在输入 setter 或其他更改对象状态的方法时立即引发事件,然后继续可能发生的任何防护和验证。
因此,我将该事件视为属性可能更改但尚未更改的通知,并且可能实际上并未成功完成更改。
如果对象的使用者正在使用此属性(例如 LINQ to SQL 使用事件进行更改跟踪),我是否应该推迟并仅在验证了我给出的值是否正确并且对象的状态对于更改是否有效?
此活动的合同是什么?订阅者会有什么副作用?
INotifyPropertyChanged is fairly self explanatory and I think I'm clear on when to raise that one (i.e. when I've finished updating the values).
If I implement INotifyPropertyChanging I'm tending to raise the event as soon as I enter the setter or other method that changes the objects state and then continue with any guards and validations that may occur.
So I'm treating the event as a notification that the property may change but hasn't yet been changed, and might not actually finish changing successfully.
If consumers of the object are using this property (like let's say LINQ to SQL using the event for change tracking) should I be holding off and only raising the event once I have validated that the the values I've been given are good and the state of the object is valid for the change?
What is the contract for this event and what side effects would there be in subscribers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果为您的对象指定的值对该属性无效并且您抛出异常,则不应引发
PropertyChanging
事件。 仅当您决定值将会发生变化时,才应该引发该事件。 典型的使用场景是更改一个简单的字段:If your object is given a value that is invalid for the property and you throw an exception then you shouldn't raise the
PropertyChanging
event. You should only raise the event when you've decided that the value will change. The typical usage scenario is for changing a simple field:顺便说一句 - PostSharp 具有自动实现 INotifyPropertyChanged 的有趣功能 - 像这样。
As an aside - PostSharp has the interesting ability to auto-implement INotifyPropertyChanged - like so.
如果您想完全避免实现 INotifyPropertyChanged,请考虑使用 更新控件 .NET。 这消除了几乎所有的簿记代码。
If you would like to avoid implementing INotifyPropertyChanged altogether, consider using Update Controls .NET instead. This eliminates almost all of the bookkeeping code.