在我当前的项目中,我使用的类实现了以下ITransaction
接口,如下所示。这是可以撤消的事务的通用接口。我也有一个TransactionSet
类,用于尝试多个事务或事务集,并最终可用于创建事务树。可以从Dispose()中引发事件吗?
ITransaction
的某些实现会保留对对象实例或对象的临时引用,以便在以后调用Undo()
时使用。稍后可以确认成功的交易,之后不再允许Undo()
,并且因此也不再需要临时数据。目前我使用Dispose()
作为我的确认方法来清理任何临时资源。
但是,现在我希望我的交易也能够引发事件以通知其他类别发生了什么。除非交易确认,否则我不希望事件触发。因为我不希望允许事务通过撤消多次激发事件,然后再次运行。
由于我使用Dispose()
来确认事务是否还存在任何错误,因此也从这些事件中引发了这些事件?或者,在我的界面上单独使用Confirm()
方法会更好,除了清除临时数据的Dispose()
之外还会触发事件?我不能想到任何我想确认的情况,但不能处理交易。然而,我不清楚我在Dispose()
内应该做什么和不该做什么。
public enum TransactionStatus
{
NotRun, // the Transaction has not been run, or has been undoed back to the original state
Successful, ///the action has been run and was successful
Error //there was an attempt to run the action but it failed
}
/// <summary>
/// Generic transaction interface
/// </summary>
public interface ITransaction
{
TransactionStatus Status { get; }
/// <summary>
/// Attempts the transaction returns true if successful, false if failed.
/// If failed it is expected that everything will be returned to the original state.
/// Does nothing if status is already Successful
/// </summary>
/// <returns></returns>
bool Go();
/// <summary>
/// Reverts the transaction
/// Only does something if status is successful.
/// Should return status to NotRun
/// </summary>
void Undo();
/// <summary>
/// A message describing the cause of the error if Status == Error
/// Otherwise equal String.Empty
/// </summary>
string ErrorMessage { get; }
}
许多.net类都有一个“Disposing”事件,如果没有这个事件将非常困难。如果一个对象将持有对其他地方可能使用或可能不会使用的IDisposable的引用(例如,一个持有BackgroundImage的控件),则可以使用Disposing事件来允许主对象的持有者在必要时清理嵌套对象。 – supercat 2011-03-15 17:52:59