gpt4 book ai didi

c# - 从 Dispose() 触发事件是否可以?

转载 作者:太空狗 更新时间:2023-10-29 17:51:18 25 4
gpt4 key购买 nike

在我当前的项目中,我使用的类实现了如下所示的 ITransaction 接口(interface)。这是可以撤消的事务的通用接口(interface)。我还有一个 TransactionSet 类,用于尝试多个事务或 TransactionSet,最终可用于创建事务树。

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; }
}

最佳答案

Dispose 不是一种特殊的方法——它不像构造函数或终结器或其他任何东西——它只是一种有用的模式,用于通知对象消费者已使用完它。它没有理由不能引发事件。

关于c# - 从 Dispose() 触发事件是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3252404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com