INotifyPropertyChanging 和验证:何时引发 PropertyChanging?

发布于 2024-07-06 07:36:57 字数 330 浏览 12 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌︼了一个春 2024-07-13 07:36:57

如果为您的对象指定的值对该属性无效并且您抛出异常,则不应引发 PropertyChanging 事件。 仅当您决定值将会发生变化时,才应该引发该事件。 典型的使用场景是更改一个简单的字段:

public T Foo
 { get
    { return m_Foo;
    }
   set
    { if (m_Foo == value) return; //no need for change (or notification)
      OnPropertyChanging("Foo");
      m_Foo = value;
      OnPropertyChanged("Foo");
    }
 }

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:

public T Foo
 { get
    { return m_Foo;
    }
   set
    { if (m_Foo == value) return; //no need for change (or notification)
      OnPropertyChanging("Foo");
      m_Foo = value;
      OnPropertyChanged("Foo");
    }
 }
徒留西风 2024-07-13 07:36:57

顺便说一句 - PostSharp 具有自动实现 INotifyPropertyChanged 的​​有趣功能 - 像这样

As an aside - PostSharp has the interesting ability to auto-implement INotifyPropertyChanged - like so.

苍暮颜 2024-07-13 07:36:57

如果您想完全避免实现 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文