[VB.NET] ByVal 和 ByRef 的區別

  • 1495
  • 0

摘要:[VB.NET] ByVal 和 ByRef 的區別

ByVal (By Value)

When you pass an argument by value, the procedure sees only a copy of the argument. Even if the procedure changes this copy, the changes aren’t reflected in the original variable passed to the procedure. The benefit of passing arguments by value is that the argument values are isolated from the procedure and only the code segment in which they are declared can change their values.

ByRef (By Address)

Arguments passed by reference are prefixed by the keyword ByRef in the procedure’s definition. The procedure has access to the original values of the arguments passed by reference and can modify them.


Module Module1
    Dim sum As Integer

    Sub Main()

        Dim value As Integer = 1

        ' The integer value doesn't change here when passed ByVal.
        Example1(value)

        Console.WriteLine("1:get value :" & value)
        Console.WriteLine("1:get sum :" & sum)

        ' The integer value DOES change when passed ByRef.
        Example2(value)

        Console.WriteLine("2:get value :" & value)
        Console.WriteLine("2:get value :" & sum)
    End Sub

    Sub Example1(ByVal test As Integer)
        If test = 3 Then
            sum = 11
        
        End If
        Console.WriteLine("Example1:" & sum)
    End Sub

    Sub Example2(ByRef test As Integer)
        If test = 3 Then
            sum = 11
        Else
            sum = 2
        End If
        Console.WriteLine("Example2:" & sum)
    End Sub
End Module