如果出现条件,我必须停止当前方法调用的执行,并返回到方法调用.how之前的状态。假设我正在执行某个示例方法,并且发生了一个条件,我正在提示一个消息框,然后我想返回到此函数调用之前的状态
发布于 2009-04-14 06:48:01
您可以使用Memento pattern实现对象回档。来自here的。
管理员将对创建者执行某些操作,但希望能够撤消更改。管理员首先向发起人索要纪念品。然后,它执行它要执行的任何操作(或操作序列)。为了回滚到操作之前的状态,它将memento对象返回给发起者。
收到指示应回滚的事件后,可以撤消更改并返回到调用方。这里有一些关于为什么不应该使用Thread.Abort的info. and links。
发布于 2009-04-14 06:53:14
如果我没理解错的话,你希望在某些条件为真的情况下撤销对某些变量所做的更改?如果是这种情况,您将需要存储所有变量(或作为一个整体的类)的副本。然后,如果您的条件为真,那么在从函数返回之前,您必须将所有这些变量恢复到它们的初始状态。它应该是这样的:
// In order to clone your variable, you may need to inherit from
// ICloneable and implement the Clone function.
bool MyFunction(ICloneable c)
{
// 1. Create a copy of your variable
ICloneable clone = c.Clone();
// 2. Do whatever you want in here
...
// 3. Now check your condition
if (condition)
{
// Copy all the attributes back across to c from your clone
// (You'll have to write the ResetAttributes method yourself)
c.ResetAttributes(clone);
// Put a message box up
MessageBox.Show("This failed!");
// Now let the caller know that the function failed
return false;
}
else
{
// Let the caller know that the function succeeded
return true;
}
}发布于 2009-04-14 07:08:33
堆上的通用回滚功能对我来说是闻所未闻的。但是您可以使用命令模式来获取撤消功能,并将其用于回滚:
http://en.wikipedia.org/wiki/Command_pattern
从本质上讲,您将操作封装在一个对象中,该对象存储了足够的更改信息,从而可以撤消更改。您将该对象推送到堆栈上,当您的条件发生时,您可以从堆栈中弹出所有命令对象并撤消它们。如果没有更多关于你的案例的信息,就很难给出更具体的信息或判断这是否适用于你。
https://stackoverflow.com/questions/746548
复制相似问题