从 C# 中的函数退出
一个基本问题。我需要退出函数而不引发任何异常。我如何在 C# 中做到这一点?
A basic question. I need to exit a function without throwing any exceptions. How do I do that in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
很简单:
It's as simple as:
我不确定我是否正确理解了你的意思。也许使用
return;
?I'm not sure I understand you correctly. Maybe using
return;
?而不是使用“返回;”我总是提出正确的逻辑。
换句话说,您不需要从某些方法中退出执行:只需使用条件语句,这样如果某些布尔值不为 true,则意味着某些代码不得执行。
但我认为这是我的观点,其他人更喜欢将控制权返回给调用者。
此外,您想知道基于异常的流控制是一种反模式。
Instead of using "return;" I've always suggested a right logic.
In other words, you don't need to leave execution from some method: just use a conditional statement so if some boolean isn't true, that would mean some code mustn't be executed.
But I assume this is my opinion, and others prefer returning the control to the caller.
Additionally, you'd like to know exception-based flow control is an anti-pattern.
使用 return 或 break 关键字……但请确保这些语句后面没有任何内容,因为您可能有无法访问的代码。此外,代码中存在多个退出也会导致将来难以维护
Use the return or break keywords ...... But make sure nothing is after these statements as you may have unreachable code. Also having multiple exits in your code can make it difficult to maintain in the future
您可以将代码放在 try catch 块中,并在 finally 块中执行您想做的任何操作,而不必担心异常。
you can put you code in a try catch block and do whatever you want to do in the finally block without worrying about the exception.
可能是将 catch 块保持为空。请解释你的问题
May be to Keep the catch block empty. Please explain your question