其他语言中的 VBA With 语句等效项
在 VBA 中,有一个很酷的功能,称为 With
语句,它可以让您设置代码块的全局范围。这对于更改对象的多个字段和调用方法很有用。
下面是一个示例:
With Forms!main
.Filter = "tel IS NOT NULL"
.FilterOn = True
.Requery 'This is a method!
If .Recordset.RecordCount> 3 Then
.BackColor = "Red"
End If
End With
在此示例中,所有以 .
开头的语句都引用 Forms!main
的字段和方法。
我还没有在任何现代语言(Javascript、C#、Python)中遇到过这样的功能,我想知道这是否有原因?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一篇有用的维基百科文章将其描述为方法级联,基本上是一种语法糖。文章包括 dart、pascal 和 smalltalk 为具有此功能的其他语言。
它也是用 Javascript 编写的,但是注意那:
根据这个答案,它也包含在 C# 9.0 中 - 阅读上下文的所有答案。
另一篇有趣的文章是这篇文章,其中有一些我对“为什么”这个功能没有更广泛的问题的回答很有趣。
“糖”可能会变得“太甜”,例如:
与您更简洁和可读的示例相比,突然使用
With
并不那么有用。我们可以看到该功能引起了争议(由于过度使用),这就是它尚未真正成为主流的原因。There's a useful Wikipedia article that describes this as method cascading, basically a type of syntactic sugar. The article includes dart, pascal and smalltalk as other languages with this feature.
It's in Javascript as well, but note that:
And it's also included in C# 9.0 according to this answer - read all the answers for context.
The other interesting post is this one which has some of the flavour for my answer to the question of 'why' this feature is not more widespread.
The 'sugar' can get 'too sweet' e.g.:
Suddenly use of
With
is not as useful compared to your more terse and readable example. We can see the feature generates controversy (due to over-use) and this is why it has not really made it into the mainstream.