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

前端 未结 1 1313
栀梦
栀梦 2020-12-22 13:45

Example:

Dim a As Integer = 1
Dim b As Integer = a
Console.WriteLine(b)
a = 0
Console.WriteLine(b)

Output:

1
0
相关标签:
1条回答
  • 2020-12-22 13:51

    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
    

    Value Type

    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
    

    Reference Type

    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"

    0 讨论(0)
提交回复
热议问题