Visual Basic 6.0 按值传递参考差异

发布于 2024-07-27 13:37:17 字数 382 浏览 10 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黒涩兲箜 2024-08-03 13:37:18

当您在单行上调暗多个变量时,即 Dim i, j as Integer j 被调暗为整数,但 i 是一个变体。 您需要显式声明每个变量类型。 我更喜欢每行只包含一个变量。

Dim i As Integer, j As Integer

或者

Dim i As Integer
Dim j As Integer

这是我继承另一个程序员的代码时学到的东西

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.

Dim i As Integer, j As Integer

or

Dim i As Integer
Dim j As Integer

This is something I learned when I inherited another programmer's code

心清如水 2024-08-03 13:37:18

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文