是否可以从另一个方法中断/返回方法执行?
我有这样的事情:
void MethodToBreak()
{
// do something
if(something)
{
MethodThatBreaks();
return;
}
// do something
}
void MethodThatBreaks()
{
// do something
}
所以,我想知道:是否可以从以下位置中断执行:MethodThatBreaks()
?然后,我会: if(something) MethodThatBreaks();
并且如果 if
内的条件为 true,则该行之后的任何内容都不会被执行。
注意:我知道在这种情况下可以使用 else
,但我不希望这样。
I have something like this:
void MethodToBreak()
{
// do something
if(something)
{
MethodThatBreaks();
return;
}
// do something
}
void MethodThatBreaks()
{
// do something
}
So, I was wondering: is it possible to break execution from: MethodThatBreaks()
? Then, I would have: if(something) MethodThatBreaks();
and if the condition inside if
is true, nothing after that row would be executed.
NOTE: I know it's possible with else
in this case, but I don't want that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你要扰乱一个方法的执行,那么维护起来将是一场噩梦。试图弄清楚为什么你的控制流在六个月后到处都是,或者对于另一个开发人员来说,会引发动脉瘤。
尽管我个人会使用
else
,但您已经在那里做的事情没有任何问题。您不想使用else
是否有特殊原因?如果剩余的代码太长,则可能表明您应该重构。It would be a nightmare to maintain if you were to upset execution of one method from another. Trying to figure out why your control flow is all over the place six months down the line, or for a another developer, would be aneurysm-inducing.
There's nothing wrong with what you're already doing there, although personally I'd use an
else
. Is there a particular reason why you don't want to useelse
? If it's that the remaining code is too long that's perhaps and indication you should refactor.一种可能是在
MethodThatBreaks
中引发异常。因此,在MethodToBreak
的客户端中,您放置了 try catch 块。Throwing an exception in
MethodThatBreaks
is one possibility. So in the client of theMethodToBreak
you put try catch block.这可以通过以下方式完成:
声明全局变量
This can be done by:
declare global variable