[英]What is the best way to avoid goto?
I usually fall into a situation where goto seems to be the best option to my mind. 我通常会陷入goto似乎是我心中最好的选择的情况。 But I have read several times not to use it, and there is always an alternative.
但是我已经读过好几次不使用它了,并且总有一种选择。 Now, I am trying something like this:-
现在,我正在尝试这样的事情:
try{
//Something that requires internet connectivity;
}
catch{
//Show a message-Internet connectivity lost,and go back to try
//-->FYI--Ignore "show message", because I am just appending this text to a
// textbox. So there won't be a problem of multiple ShowMessage Boxes.
}
Now, the best option seems to me is to use goto in catch statement, but I am trying to avoid it. 现在,在我看来,最好的选择是在catch语句中使用goto,但我试图避免这种情况。 try is the first statement in a function, and if I recall that function, I am piling up stacks, so thats not a better option as well.
try是函数中的第一条语句,如果我记得该函数,则说明正在堆积堆栈,因此这也不是更好的选择。 What alternative can I take?
我可以采取什么替代方法?
Use a while
loop with a flag 使用带有标志的
while
循环
var tryAgain = true;
while (tryAgain)
{
try
{
...
tryAgain = false;
}
catch (...)
{
tryAgain = ...
}
}
In this particular case there is nothing wrong with calling the same function recursively and keeping a counter with the number of times you've called it. 在这种特殊情况下,递归调用相同的函数并与您调用它的次数保持一致是没有错的。 Something like this (in pseudo code):
这样的东西(用伪代码):
public void DoMyInternetThing(int numberOfAttemptsRemaining)
{
try
{
//do stuff
}
catch (ConnectionException)
{
if (numberOfAttemptsRemaining <= 0)
throw new SomethingBadHappenedException();
DoMyInternetThing(numberOfAttemptsRemaining - 1);
}
}
As with anything recursive you need to ensure you structure it correctly, but this works nicely (I've used it myself) and it avoids your goto
(which is not bad in itself, but use of it can lead to spaghetti or badly structured code). 与任何递归方法一样,您需要确保正确地构造它,但这很好用(我自己使用过),并且避免了
goto
(它本身并不坏,但是使用它可能导致意大利面条或结构错误的代码) )。
如果要重试,请将try-catch包装在do-while循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.