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.

備註Remarks

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

Declare 陳述式Declare Statement

Function 陳述式Function Statement

Operator 陳述式Operator Statement

Property 陳述式Property Statement

Sub 陳述式Sub Statement

範例Example

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