如何使 IEditableObject.EndEdit 原子化?
如果我有一个实现 IEditableObject 的 Address 对象,我可能会有这样的 EndEdit 实现:
public void EndEdit()
{
// BeginEdit would set _editInProgress and update *Editing fields;
if (_editInProgress)
{
_line1 = _line1Editing;
_line2 = _line2Editing;
_city = _cityEditing;
_state = _stateEditing;
_postalCode = _postalCodeEditing;
_editInProgress = false;
}
}
例如,如果更新 _state 时出现异常,则所有 5 个属性都应重置。 此原子更新问题可能不仅限于 EndEdit。
If I have an Address object which implements IEditableObject, I might have EndEdit implementation like this:
public void EndEdit()
{
// BeginEdit would set _editInProgress and update *Editing fields;
if (_editInProgress)
{
_line1 = _line1Editing;
_line2 = _line2Editing;
_city = _cityEditing;
_state = _stateEditing;
_postalCode = _postalCodeEditing;
_editInProgress = false;
}
}
If there is an exception updating _state, for example, then all 5 properties should reset. This atomic update issue probably isn't limited to EndEdit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,肯特想知道为什么设置字段会引发异常是正确的。
忽略这个问题; 您可以使用一个简单的方法:
复杂的问题是每个字段的重置值由什么构成?
如果您需要“重置”到最后一个值,那么您可能需要某种方法来在对其执行某些操作之前轻松存储对象状态,以及如果出现问题,能够轻松恢复该状态。 查看 Momento 模式处理这个问题的方法。
First off, Kent is correct in wondering why setting a field would throw an exception.
Ignoring that question; you could just use a simple:
The complications come in with regards to what constitutes the reset value for each field?
If you need to "reset" to the last value then you'll likely want some way to easily store the object state before doing something to it, along with the ability to easily restore that state should something go wrong. Check out the Momento Pattern on a nifty way to deal with that problem.
我不使用字段来存储值。 相反,我使用属性可以读写的哈希表。 这给了我一个非常简单的设计。
I don't use fields for storing values. Instead I use a hash table that the properties can read and write. This gives me a really simple design.