2

我在 vb.net 中有一个类定义为公共类 A

A 类在 Load 上创建,每个程序循环调用一次

类 A 的构造函数包含参数(byref Value as long)

我有一个名为 varB 的全局变量,它在创建时传递给 A 类。

现在为什么在程序循环期间更改 varB 时,更改不会反映在类中?

4

1 回答 1

2

If only that was so simple... ByRef only works inside the sub/function you called, to modifiy the variable you 'send', and after returning from that sub/function, no more changes are made.

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

So if you want to have the value, you have to use an object (define new 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

But notice that a change on ValueFromClassTwo will be reflected, but not notified : use a public shared event in ClassTwo to notify / Add an event Handler in ClassOne to get notified.

于 2012-05-05T20:17:20.073 回答