[英]Strange behaviour with strings and arrays
Here I assign the value of an array to a variable, I then alter the variable, the array changes also. 在这里,我将数组的值分配给变量,然后更改变量,数组也会发生变化。
$TestArray = @{ "ValueA" = "A" ; "ValueB" = "B" ; "Number" = "" }
$TestNumbers = 1..10
foreach ($number in $testnumbers) {
$results = $TestArray
$results.Number = $number
Write-Host $TestArray.Number
}
I thought that $results = $TestArray
would take a copy of $TestArray
but this test shows that modifying $results
also changes the corresponding value in $TestArray
我认为,
$results = $TestArray
将采取的副本$TestArray
但试验表明,修改$results
也改变了相应的价值$TestArray
Can anyone help me understand this behavior? 谁能帮助我了解这种行为?
Doing: 这样做:
$results = $TestArray
will make $results
a reference to the same object referred to by TestArray
. 将使
$results
引用由TestArray
引用的同一对象。 So, if you change one, the other will also be affected because they are the same object. 因此,如果更改一个,则另一个也会受到影响,因为它们是同一对象。
To instead make $results
a copy of $TestArray
, you can use its Clone
method : 要代替
$results
复制 $TestArray
,可以使用其Clone
方法 :
$results = $TestArray.Clone()
Also, just for the record, $TestArray
is not actually an array. 另外,仅作记录,
$TestArray
实际上不是数组。 It is a hashtable (also called a hashmap) where keys are paired with values. 它是一个哈希表 (也称为哈希图),其中键与值配对。 An array would be something like:
数组将类似于:
$TestArray = (1, 2, 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.