Visual Basic 6.0传递值参考差异

时间:2022-02-28 15:30:50

In the following code, I get a compile time error because i is treated as a variant. The error is: "ByRef Argument type mismatch.".

在下面的代码中,我得到一个编译时错误,因为我被视为一个变体。错误是:“ByRef Argument type mismatch。”。

But if I pass the parameters ByVal, there is no error why?

但是,如果我传递参数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

2 个解决方案

#1


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.

ByVal将变量自动转换为整数,因为它传递了一个值。而ByRef试图传递一个可以在子程序中修改的变量。本质上,我在ByRef场景中是X. VB6不允许您将变量修改为整数。

#2


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,j作为整数j变暗为整数,但我是一个变体。您需要显式声明每个变量类型。我更喜欢每行只包含一个变量。

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

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

#1


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.

ByVal将变量自动转换为整数,因为它传递了一个值。而ByRef试图传递一个可以在子程序中修改的变量。本质上,我在ByRef场景中是X. VB6不允许您将变量修改为整数。

#2


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,j作为整数j变暗为整数,但我是一个变体。您需要显式声明每个变量类型。我更喜欢每行只包含一个变量。

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

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