为什么要“呼叫"?带有参数的类的方法是否需要关键字? [英] Why is the "Call" keyword required for methods of classes that take parameters?

查看:27
本文介绍了为什么要“呼叫"?带有参数的类的方法是否需要关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课有多种方法.一些方法采用参数.这些方法需要关键字"Call"才能起作用.为什么?

My class has multiple methods. Some methods take parameters. Those methods require the keyword "Call" to work. Why?

MyObject.MyMethod   'Works just fine without Call.

Call MyObject.MyMethod(arg1, arg2)  'Requires Call. Won't compile without it.

推荐答案

Call 不再需要.实际上,自从隐式调用语法在Visual Basic 4.0中问世以来,如果我没记错的话,它已经过时了.

Call is never required. In fact it's been obsolete since the advent of implicit call syntax in... Visual Basic 4.0, if I recall correctly.

object.MemberName arg1, arg2

请注意括号已消失.正如您指出的那样,这将是非法的:

Notice the parentheses are gone. This would be illegal, as you noted:

object.MemberName (arg1, arg2)

注意 MemberName 和开头(括号,将其作为表达式进行评估,然后将结果按值传递(无论成员的签名是否明确指定 ByRef ,无论该签名是否明确)给要调用的成员".除了(foo,bar)不是合法表达式之外,因此代码无法编译.

Notice the whitespace between MemberName and the opening (: the VBE will always put a space there. That's the VBE saying "Ok so I'll take what's in these parentheses, evaluate that as an expression, and pass the result by value (regardless of the member's signature specifying ByRef, explicitly or not) to the member you're invoking". Except (foo, bar) isn't a legal expression, so the code doesn't compile.

MemberName 返回调用者需要捕获的值时,括号的行为会有所不同:

When MemberName returns a value that the caller needs to capture, the parentheses behave differently:

foo = object.MemberName(arg1, arg2)

请注意,现在不再有空格;如果添加任何VBE,它将删除它.

Notice there's no whitespace anymore; the VBE will remove it if you add any.

因此,举一个更熟悉和具体的示例-请注意,它与对象和对象无关.成员:

So with a more familiar and concrete example - note that it has nothing to do with objects & members:

MsgBox "Yes?", vbYesNo ' works fine
Call MsgBox("Yes?", vbYesNo) ' works fine
Call VBA.Interaction.MsgBox("Yes?", vbYesNo) ' works fine
MsgBox ("Yes?", vbYesNo) ' illegal
result = VBA.Interaction.MsgBox("Yes?", vbYesNo) ' works fine

Call 关键字仅在VBA6/VBA7中用于向后兼容,与许多许多其他语言构造( While ... Wend ).这就是为什么 Rubberduck (免责声明:我是该开源项目的管理员之一)将其使用标记为过时",并提供删除它的工具.

The Call keyword only exists in VBA6/VBA7 for backward-compatibility purposes, like many, many other language constructs (While...Wend comes to mind). That's why Rubberduck (disclaimer: I'm one of the admins of that open-source project) flags its use as "obsolete", and provides tooling to remove it.

这篇关于为什么要“呼叫"?带有参数的类的方法是否需要关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆