我在vb.net中有一个定义为公共类A
的类类A在Load上创建,每个程序循环调用一次
A类的构造函数包含参数(byref Value as long)
我有一个名为varB的全局变量,它在创建时传递给A类。
现在为什么在程序循环期间更改varB时,更改不会反映在类中?
答案 0 :(得分:2)
如果只是那么简单...... ByRef只能在您调用的子/函数内部工作,以修改您“发送”的变量,并且从该子/函数返回后,不再进行任何更改。
Public Class ClassOne
Public ValuefromClassOne As Integer
Public Sub ChangeAValue(ByRef AValue As Integer)
AValue = 12 ' This will modifiy the variable
ValuefromClassOne = AValue ' this will ONLY put 12 inside ValueFromClassOne
End Sub
End Class
Public Class ClassTwo
Public ValueFromClassTwo As Integer
Public Sub CallToClassOne()
ChangeAValue(ValueFromClassTwo) ' this will ONLY put 12 into ValueFromClassTwo
ValueFromClassTwo = 25 ' this will have effect only on ValueFromClassTwo - no link
End Sub
End Class
因此,如果您想拥有该值,则必须使用一个对象(定义新类)
Public Class IntegerHolder
Public Property AnInteger As Integer
End Class
Public Class ClassOne
Public ValuefromClassOne As IntegerHolder
Public Sub ChangeAValue(ByVal AValue As IntegerHolder)
AValue.AnInteger = 12 ' This will modifiy the variable
ValueFromClassOne.AnInteger = AValue.AnInteger ' this will ONLY put 12 inside ValueFromClassOne
' !!!!! BUT with this : !!!!
ValueFromClassOne = AValue
' Now you hold a copy of the variable given in argument of ChangeAValue
End Sub
End Class
Public Class ClassTwo
Public ValueFromClassTwo As New IntegerHolder
Public Sub CallToClassOne()
ChangeAValue(ValueFromClassTwo) ' this will ONLY put 12 into ValueFromClassTwo
ValueFromClassTwo.AnInteger = 25 ' this will have effect on
' ValueFromClassTwo AND ValuefromClassOne
End Sub
End Class
但请注意,ValueFromClassTwo的更改将被反映,但不会 通知:使用ClassTwo中的公共共享事件来通知/添加事件 ClassOne中的处理程序以获得通知。