Επεξεργασία

Κοινή χρήση μέσω


ByVal (Visual Basic)

Specifies that an argument is passed by value, so that the called procedure or property cannot change the value of a variable underlying the argument in the calling code. If no modifier is specified, ByVal is the default.

Note

Because it is the default, you do not have to explicitly specify the ByVal keyword in method signatures. It tends to produce noisy code and often leads to the non-default ByRef keyword being overlooked.

Remarks

The ByVal modifier can be used in these contexts:

Declare Statement

Function Statement

Operator Statement

Property Statement

Sub Statement

Example

The following example demonstrates the use of the ByVal parameter passing mechanism with a reference type argument. In the example, the argument is c1, an instance of class Class1. ByVal prevents the code in the procedures from changing the underlying value of the reference argument, c1, but does not protect the accessible fields and properties of c1.

Module Module1

    Sub Main()

        ' Declare an instance of the class and assign a value to its field.
        Dim c1 As New Class1()
        c1.Field = 5
        Console.WriteLine(c1.Field)
        ' Output: 5

        ' ByVal does not prevent changing the value of a field or property.
        ChangeFieldValue(c1)
        Console.WriteLine(c1.Field)
        ' Output: 500

        ' ByVal does prevent changing the value of c1 itself. 
        ChangeClassReference(c1)
        Console.WriteLine(c1.Field)
        ' Output: 500

        Console.ReadKey()
    End Sub

    Public Sub ChangeFieldValue(ByVal cls As Class1)
        cls.Field = 500
    End Sub

    Public Sub ChangeClassReference(ByVal cls As Class1)
        cls = New Class1()
        cls.Field = 1000
    End Sub

    Public Class Class1
        Public Field As Integer
    End Class

End Module

See also