从 VB.NET With 块退出
在下面的代码块中,如果 Var1 = 2
,VB.NET 是否正常退出 With 块?
With MyObject
.Property1 = "test"
If Var1 = 2 Then
Return True
End If
.Property2 = "Test2"
End With
Return False
我记得这是 VB6 中的一个问题,并导致令人头痛的不可预测的行为 - VB.NET 也是如此吗?
In the following block of code, does VB.NET gracefully exit the With block if Var1 = 2
?
With MyObject
.Property1 = "test"
If Var1 = 2 Then
Return True
End If
.Property2 = "Test2"
End With
Return False
I remember this being an issue in VB6 and causing headaches with unpredicable behaviour - is the same true of VB.NET?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 MSDN,这仍然是不可能的:
如果您需要退出在执行所有语句之前,在 End With 语句上放置一个标签,并使用 GoTo 语句分支到该语句。 (...) 您无法将控制从 With 块外部转移到其内部,或从其内部转移到外部。您可以从块内部调用过程,但控制权返回到以下语句。
According to MSDN, this still isn't possible:
If you need to exit before all the statements have been executed, put a label on the End With statement and use the GoTo Statement to branch to it. (...) You cannot transfer control either from outside a With block to inside it, or from inside it to the outside. You can call a procedure from inside the block, but control returns to the following statement.
不得不在这里添加另一个答案,因为我主要是好奇。从来没有用过太多,而且我不记得曾经过早退出该块,但我刚刚在 VB2010 下测试了它,它似乎工作得很好(即正如我所期望的那样,换句话说......
如果 Var1 =2 ,该函数返回 TRUE,并且 MyObject.Property1 的值是“Test”,但 MyObject.Property2 尚未设置。
它可能在测试中以这种方式工作,但在一个相当大的实际应用程序中,并且关闭了调试。等等,等等,它的工作方式可能会有所不同,所以,需要考虑......
Had to add another answer here, because I was mainly curious. Never used WITH much, and I can't recall ever exiting the block prematurely, but I just tested this under VB2010 and it appears to work just fine (ie as I would expect it to, in other words...
If Var1 =2, the function returns TRUE, and the value of MyObject.Property1 is "Test" but MyObject.Property2 has not be set.
It's possible that it worked this way in a test, but in a real app of significant size, with debugging turned off etc, etc, it could work differently, so, there's that to consider....