Visual Basic: Variable that references another variable changes when original vairable changes

独自空忆成欢 提交于 2019-11-29 18:15:21

Integer is a Value type so when you assign 'a' to 'b' a COPY is made. Further changes to one or the other will only affect that particular copy in its own variable:

Module Module1

    Sub Main()
        Dim a As Integer = 1
        Dim b As Integer = a

        Console.WriteLine("Initial State:")
        Console.WriteLine("a = " & a)
        Console.WriteLine("b = " & b)

        a = 0
        Console.WriteLine("After changing 'a':")
        Console.WriteLine("a = " & a)
        Console.WriteLine("b = " & b)

        Console.Write("Press Enter to Quit...")
        Console.ReadLine()
    End Sub

End Module

If we are talking about Reference types, however, then it's a different story.

For example, that Integer might be encapsulated in a Class, and Classes are Reference types:

Module Module1

    Public Class Data
        Public I As Integer
    End Class

    Sub Main()
        Dim a As New Data
        a.I = 1
        Dim b As Data = a

        Console.WriteLine("Initial State:")
        Console.WriteLine("a.I = " & a.I)
        Console.WriteLine("b.I = " & b.I)

        a.I = 0
        Console.WriteLine("After changing 'a.I':")
        Console.WriteLine("a.I = " & a.I)
        Console.WriteLine("b.I = " & b.I)

        Console.Write("Press Enter to Quit...")
        Console.ReadLine()
    End Sub

End Module

In this second example assigning 'a' to 'b' makes 'b' a REFERENCE to the same instance of Data() that 'a' points to. Therefore changes to the 'I' variable from either 'a' or 'b' will be seen by both, since they both point to the same instance of Data().

See: "Value Types and Reference Types"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!