使用 属性 作为 byref 参数调用函数会导致调用 set 方法

Calling function with property as byref argument causes set method call

当以 属性 作为参数调用函数时,通过引用声明,属性 的 set 方法在函数调用后执行。

如果您尝试将 属性 传递到具有 ref 的函数中,如果在 c# 中完成,这会抛出一个编译器错误,但在 vb.net 中,这会发生。这是一个错误吗?怎么回事?

Module Module1

    Private _testProp As Integer
    Property testProp As Integer
        Get
            Return _testProp
        End Get
        Set(value As Integer)
            Console.WriteLine("changed TestProp to " & value.ToString())
            _testProp = value
        End Set
    End Property

    Private Sub testFunction(ByRef arg As Integer)
        Console.WriteLine(arg)
    End Sub

    Sub Main()
        Console.WriteLine("explicit set to 5 in main")
        testProp = 5
        Console.WriteLine("calling function")
        testFunction(testProp)
        Console.ReadKey()
    End Sub

End Module

输出:

explicit set to 5 in main
changed TestProp to 5
calling function
5
changed TestProp to 5

将 属性 传递给 ByRef 参数会导致 属性 被 copy-in/copy-out 传递。 VB 语言规范指出,

Copy-in copy-back. If the type of the variable being passed to a reference parameter is not compatible with the reference parameter's type, or if a non-variable (e.g. a property) is passed as an argument to a reference parameter, or if the invocation is late-bound, then a temporary variable is allocated and passed to the reference parameter. The value being passed in will be copied into this temporary variable before the method is invoked and will be copied back to the original variable (if there is one and if it's writable) when the method returns.

所以这显然是设计使然,而不是错误。