指定参数 由值传递,以便调用的过程或属性无法更改调用代码中自变量的变量的值。 如果未指定修饰符,则 ByVal 是默认值。
注释
因为它是默认值,因此无需在方法签名中显式指定 ByVal
关键字。 它倾向于生成干扰代码,通常会导致忽略非默认 ByRef
关键字。
注解
修饰 ByVal
符可用于以下上下文:
示例:
以下示例演示如何使用 ByVal
具有引用类型参数的参数传递机制。 在此示例中,参数是 c1
类 Class1
的实例。
ByVal
防止过程中的代码更改引用参数的基础值, c1
但不保护可访问的字段和属性 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