Visual Basic 6.0 按值传递参考差异
在下面的代码中,我收到编译时错误,因为 i
被视为变体。 错误是:“ByRef Argument类型不匹配。”。
但是如果我传递参数ByVal
,没有错误,为什么?
Private Sub Command2_Click()
Dim i, j As Integer
i = 5
j = 7
Call Swap(i, j)
End Sub
Public Sub Swap(ByRef X As Integer, ByRef Y As Integer)
Dim tmp As Integer
tmp = X
X = Y
Y = tmp
End Sub
In the following code, I get a compile time error because i
is treated as a variant. The error is: "ByRef Argument type mismatch.".
But if I pass the parameters ByVal
, there is no error why?
Private Sub Command2_Click()
Dim i, j As Integer
i = 5
j = 7
Call Swap(i, j)
End Sub
Public Sub Swap(ByRef X As Integer, ByRef Y As Integer)
Dim tmp As Integer
tmp = X
X = Y
Y = tmp
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在单行上调暗多个变量时,即
Dim i, j as Integer
j 被调暗为整数,但 i 是一个变体。 您需要显式声明每个变量类型。 我更喜欢每行只包含一个变量。或者
这是我继承另一个程序员的代码时学到的东西
When you Dim several variables on a single line ie
Dim i, j as Integer
j is dimmed as an integer, but i is a variant. You need to declare each variable type explicitly. I prefer to include only a single variable per line.or
This is something I learned when I inherited another programmer's code
ByVal 会自动将变量转换为整数,因为它正在传递一个值。 当 ByRef 尝试传递一个您可以在子例程中修改的变量时。 本质上,I 是 ByRef 场景中的 X。 VB6 不允许您将变体修改为整数。
ByVal autoconverts the variant into a integer because it is passing a value. While the ByRef is attempting to pass a variable that you can modify in the subroutines. In essence I is X in the ByRef scenario. VB6 doesn't allow you to modify a variant as a integer.