.net - 返回最后一 block ……为什么不呢?

标签 .net try-catch-finally

作为MSDN mentions:

The code in a Finally block runs after a Return statement in a Try or Catch block is encountered, but before that Return statement executes. In this situation, a Return statement in the Finally block executes before the initial Return statement. This gives a different return value. To prevent this potentially confusing situation, avoid using Return statements in Finally blocks.



由于我对本说明的了解不多,因此我举一个例子(VB.NET,我认为在C#中情况类似):
Try
    HugeOp()
    Return "OK"
Catch
    Return "NOK"
Finally
    Return "Finally"
End Try

现在,为什么在C#和VB.NET中都应该使用非法的

最佳答案

这是非法的,因为当您到达Finally块时,已经定义了要返回的值(如果一切顺利,则为“OK”;如果捕获到异常,则为“NOK”)。如果您能够从Finally块返回一个不同的值,则无论上面的指令结果如何,都将始终返回该值。只是没有意义...

关于.net - 返回最后一 block ……为什么不呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5788134/

相关文章:

iphone - @try - Objective-C 中的 catch block

c# - 为什么 finally block 中的代码不执行?

Powershell try catch invoke-sqlcmd

c# - 像浏览器一样过滤客户端证书

.net - 是否有工具可以简化 Reflection.Emit 的工作?

.net - WCF DispatchMessageInspector - 处理并提供给操作使用

c# - 如何生成一个范围内的加密安全随机整数?

c# - 确定用户是否属于本地管理员组

java - 如何尝试......最终在内部工作