当使用属性作为声明为byref的参数调用函数时,属性的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
输出:
在main中显式设置为5 将TestProp更改为5 调用功能 五 将TestProp更改为5
将属性传递给ByRef
参数会导致属性通过copy-in / copy-out传递。 VB语言规范说明,
复制复制。如果传递给引用参数的变量类型与引用参数的类型不兼容,或者将非变量(例如属性)作为参数传递给引用参数,或者调用是后期绑定的,然后分配一个临时变量并传递给引用参数。传入的值将在调用方法之前复制到此临时变量中,并在方法返回时将其复制回原始变量(如果有的话,如果它是可写的)。
所以这显然是设计而不是错误。