【问题标题】:Visual Basic: Variable that references another variable changes when original vairable changesVisual Basic:引用另一个变量的变量在原始变量更改时发生更改
【发布时间】:2013-11-13 23:56:47
【问题描述】:

例子:

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

输出:

1
0

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

【问题讨论】:

  • 我们在 VB 中没有 DataTypeInt
  • 不要分配 b 变量 = a
  • 我赶时间,已经改正了。
  • 我用电脑查了一下,结果是1和1。
  • 请提供一个完整的示例来复制问题,它在我的计算机上按预期工作。另外你运行的是什么版本的VS?

标签: vb.net variables variable-assignment


【解决方案1】:

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

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

但是,如果我们谈论的是 Reference 类型,那就另当别论了。

例如,那个 Integer 可能被封装在一个 Class 中,而 Classes 是引用类型:

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() 实例。

见:"Value Types and Reference Types"

【讨论】:

    猜你喜欢
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多