PowerShell的Array.Add VS + = [英] PowerShell Array.Add vs +=
问题描述
我发现在PowerShell中数组一些有趣的行为,即如果我声明数组作为:
$阵列= @()
和则尝试使用 $ array.Add(项目)
方法将项目添加到它,我收到以下错误:
异常调用添加和1的说法(S):收藏是一个固定大小的
不过,如果我用追加的项目 $阵列+ =项
,该项目被接受没有问题和固定大小的限制似乎没有不适用。
这是为什么?
当您使用 $ array.Add()
方法,你要添加的元素到阵列。数组是固定大小的集合,所以你会收到一个错误。
当您使用 $阵列+ = $元素
,PS创建一个具有相同的元素为 $数组的新阵列
+您要添加,然后它会覆盖原来的一个(S)。你看有什么区别?第一种方法试图修改/扩大原有的数组,而这种方法只是复制所有元素到一个新的温度。阵列,并覆盖旧的 $阵列
-variable。
您可以使用+ =运算符将元素添加到一个数组。当你
使用
这下,Windows PowerShell实际上创建具有的价值观的新数组
原始阵列和附加值。例如,要具有添加元素
200价值在$一个变量,类型数组:$ A + = 200
块引用>来源: about_Arrays
I've found some interesting behaviour in PowerShell Arrays, namely, if I declare an array as:
$array = @()
And then try to add items to it using the
$array.Add("item")
method, I receive the following error:Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
However, if I append items using
$array += "item"
, the item is accepted without a problem and the "fixed size" restriction doesn't seem to apply.Why is this?
解决方案When you use the
$array.Add()
method, you're trying to add the element into the array. An array is a collection of fixed size, so you will recieve an error.When you use
$array += $element
, PS creates a NEW array with the same elements as$array
+ the one(s) you're adding, and then it overwrites the original. You see the difference? The first method tried to modify/expand the original array, while this approach just copies all the elements to a new temp. array, and overwrites the old one in$array
-variable.You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:
$a += 200
Source: about_Arrays
这篇关于PowerShell的Array.Add VS + =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!