Visual Basic:当原始变量更改时引用另一个变量的变量 [英] Visual Basic: Variable that references another variable changes when original vairable changes

查看:23
本文介绍了Visual Basic:当原始变量更改时引用另一个变量的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

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

输出:

1
0

由于某种原因,改变 a 也会改变 b,即使我实际上并没有改变 b.为什么会发生这种情况,我该如何解决.

For some reason changing a also changes b even though I am not actually changing b. Why does this happen, and how do I get around it.

推荐答案

Integer 是 Value 类型,因此当您将 'a' 分配给 'b' 时,COPY 是制作.对一个或另一个的进一步更改只会影响其自身变量中的特定副本:

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.

比如那个Integer可能被封装在一个Class中,Classes是Reference类型:

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

在第二个示例中,将 'a' 分配给 'b' 使 'b' 成为 REFERENCE 到 'a' 指向的同一个 Data() 实例.因此,从 'a' 或 'b' 对 'I' 变量的更改都会被两者看到,因为它们都指向同一个 Data() 实例.

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().

请参阅:"值类型和引用类型"

这篇关于Visual Basic:当原始变量更改时引用另一个变量的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆