作为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/