ByVal (Visual Basic)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. 如果未指定任何修飾詞,則預設值為 ByVal。If no modifier is specified, ByVal is the default.


因為它是預設值,所以您不需要在方法簽章 ByVal 中明確指定關鍵字。Because it is the default, you do not have to explicitly specify the ByVal keyword in method signatures. 它通常會產生雜訊的程式碼,而且經常會導致非預設的 ByRef 關鍵字被忽略。It tends to produce noisy code and often leads to the non-default ByRef keyword being overlooked.


ByVal 修飾詞可用於以下內容:The ByVal modifier can be used in these contexts:

Declare StatementDeclare Statement

Function 陳述式Function Statement

Operator StatementOperator Statement

Property StatementProperty Statement

Sub 陳述式Sub Statement


下列範例示範如何使用 ByVal 參數傳遞機制搭配參考型別引數。The following example demonstrates the use of the ByVal parameter passing mechanism with a reference type argument. 在此範例中,引數是 c1 類別的實例 Class1In the example, the argument is c1, an instance of class Class1. ByVal防止程式中的程式碼變更參考引數的基礎值,但不 c1 會保護的可存取欄位和屬性 c1ByVal 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
        ' Output: 5

        ' ByVal does not prevent changing the value of a field or property.
        ' Output: 500

        ' ByVal does prevent changing the value of c1 itself. 
        ' Output: 500

    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