如何返回一行代码并恢复调用堆栈? [英] How to return to a line of code and restore the call-stack?
问题描述
我早些时候提出了一个问题,但我认为我对自己的答案类型不够清楚希望,所以让我提供一个更具体的示例:
I asked a question earlier, but I don't think I was clear enough about the sort of answers I was hoping for, so let me provide a more concrete example:
class Program
{
private static bool State;
static void Main(string[] args)
{
State = false;
Console.WriteLine(And());
Console.ReadLine();
}
static bool And()
{
return Or() && C();
}
static bool Or()
{
return A() || AB();
}
static bool C()
{
return State;
}
static bool A()
{
return true;
}
static bool AB()
{
State = true;
return true;
}
}
该程序的流程如下:
- And()被调用
- And()调用Or()
- Or()调用A()
- A()返回true
- 流程返回Or(),后者返回true(延迟评估)
- 流返回到And(),And()调用C()
- C()返回false
- 流返回到And(),后者返回false
现在,如果Or()没有执行延迟评估(我将||
更改为|
),则程序将返回true.但是,除非整个解析结果失败(And()返回false),否则我不希望AB()执行.
Now if Or() did not perform lazy evaluation (I change ||
to |
), the program will return true. However, I don't want AB() to executed unless the result of the entire parse fails (And() returns false).
所以我想做的是,在Or()函数中的某个位置,将当前状态保存在堆栈中(静态变量),这样,如果And()返回false,我就可以从堆栈中弹出一个项目,然后尝试替代方法.
So what I'd like to do, is somewhere in the Or() function, save the current state on a stack (static variable) so that if And() returns false, I can pop an item off the stack and try the alternative.
我将如何在C#中完成此任务?
How would I accomplish this in C#?
推荐答案
它让我觉得很琐碎-只需重新安排电话:
It strikes me as being fairly trivial- just rearrange the calls:
static void Main(string[] args)
{
State = false;
Console.WriteLine(Or());
Console.ReadLine();
}
static bool Or()
{
return A() && C() || AB() && C();
}
还是我错过了什么?也许C()
有副作用,所以它不应被调用两次?
Or am I missing something? Maybe C()
has side effects such that it should not be called twice?
现在,我了解您要执行的操作.帮个忙.听取您的建议,获取GPPG副本,或者(可能更简单) ANTLR , ANTLRWorks . 所以,比尝试手动滚动解析器容易得多,并且出错率低,并且最终仍会得到C#.
Now I understand what you are trying to do. Do yourself a favor. Listen to the suggestions you've gotten, get a copy of GPPG, or (probably much simpler) ANTLR, with ANTLRWorks. It is so, so much easier and less error prone than attempting to roll a parser by hand, and you still get C# at the end.
这篇关于如何返回一行代码并恢复调用堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!