vb.net Visual Basic:当原始变量更改时引用另一个变量的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19966899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Visual Basic: Variable that references another variable changes when original vairable changes
提问by Idle_Mind
Example:
例子:
Dim a As Integer = 1
Dim b As Integer = a
Console.WriteLine(b)
a = 0
Console.WriteLine(b)
Output:
输出:
1
0
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.
出于某种原因,改变 a 也会改变 b,即使我实际上并没有改变 b。为什么会发生这种情况,我该如何解决。
回答by Idle_Mind
Integer is a Valuetype so when you assign 'a' to 'b' a COPYis made. Further changes to one or the other will only affect that particular copy in its own variable:
Integer 是一种值类型,因此当您将 '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


If we are talking about Referencetypes, however, then it's a different story.
然而,如果我们谈论的是引用类型,那就是另一回事了。
For example, that Integer might be encapsulated in a Class, and Classes are Reference types:
例如,那个 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


In this second example assigning 'a' to 'b' makes 'b' a REFERENCEto 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().
在第二个示例中,将 'a' 分配给 'b' 使 'b' 成为对 'a'指向的同一个 Data() 实例的REFERENCE。因此,'a' 或 'b' 对 'I' 变量的更改将被两者看到,因为它们都指向 Data() 的同一个实例。
See: "Value Types and Reference Types"
请参阅:“值类型和引用类型”

