Array.Add与+ = [英] Array.Add vs +=
问题描述
我在PowerShell数组中发现了一些有趣的行为,也就是说,如果我将数组声明为:
I've found some interesting behaviour in PowerShell Arrays, namely, if I declare an array as:
$array = @()
然后尝试使用$array.Add("item")
方法向其中添加项目,我收到以下错误:
And then try to add items to it using the $array.Add("item")
method, I receive the following error:
使用"1"作为参数调用添加"的异常:集合的大小固定."
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
但是,如果我使用$array += "item"
附加商品,则该商品可以毫无问题地被接受,并且固定尺寸"限制似乎并不适用.
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.
这是为什么?
推荐答案
使用$array.Add()
方法时,您试图将元素添加到现有数组中.数组是固定大小的集合,因此您将收到一个错误消息,因为它无法扩展.
When using the $array.Add()
-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.
$array += $element
创建一个 new 数组,该数组具有与旧元素相同的元素+新项目,而这个新的较大数组替换了$array
-变量
$array += $element
creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array
-variable
您可以使用+ =运算符将元素添加到数组.当你 使用 Windows PowerShell实际上使用它的值创建了一个新数组. 原始数组和附加值.例如,添加带有 值$ 200到$ a变量中的数组,键入:
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
来源: about_Arrays
+=
是一项昂贵的操作,因此当您需要添加许多项目时,应尝试以尽可能少的操作添加它们,例如:
+=
is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:
$arr = 1..3 #Array
$arr += (4..5) #Combine with another array in a single write-operation
$arr.Count
5
如果这不可能,请考虑使用更有效的集合,例如List
或ArrayList
(请参阅其他答案).
If that's not possible, consider using a more efficient collection like List
or ArrayList
(see the other answer).
这篇关于Array.Add与+ =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!