Share via


ByVal (Visual Basic)

Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code.

Comentários

The ByVal modifier can be used in these contexts:

Instrução Declare

Instrução Function (Visual Basic)

Instrução Operator

Propriedade declaração

Instrução Sub (Visual Basic)

Exemplo

O exemplo a seguir demonstra o uso do mecanismo para passar argumentos doparâmetroByValcom umargumentode tipo de referência. No exemplo, o argumento é c1, uma instância da classe Class1. ByValimpede o código nos procedimentos de alteração do valor subjacente do argumentode da referência, c1, mas não protege os campos acessíveis e propriedades do c1.

Module Module1

    Sub Main()

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

        ' ByVal does not prevent changing the value of a field or property.
        ChangeFieldValue(c1)
        Console.WriteLine("Value of field after ChangeFieldValue: " & c1.Field)

        ' ByVal does prevent changing the value of c1 itself. 
        ChangeClassReference(c1)
        Console.WriteLine("Value of field after ChangeClassReference: " & c1.Field)

    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

Consulte também

Conceitos

Passando argumentos por valor e por referência (Visual Basic)

Outros recursos

Palavras-chave (Visual Basic)