我在 PowerShell 数组中发现了一些有趣的行为,即,如果我将数组声明为:
$array = @()
然后尝试使用 $array.Add("item")
方法向其添加项目,我收到以下错误:
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
但是,如果我使用 $array += "item"
附加项目,则该项目会毫无问题地被接受,并且“固定大小”限制似乎不适用。
这是为什么?
最佳答案
当使用$array.Add()
方法时,您试图将元素添加到现有数组中。数组是固定大小的集合,因此您将收到错误,因为它无法扩展。
$array += $element
创建一个 new 数组,其元素与旧数组 + 新项相同,并且这个新的较大数组将替换旧数组中的旧数组。 $array
-变量
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
+=
是一项昂贵的操作,因此当您需要添加许多项目时,您应该尝试以尽可能少的操作添加它们,例如:
$arr = 1..3 #Array
$arr += (4..5) #Combine with another array in a single write-operation
$arr.Count
5
如果不可能,请考虑使用更高效的集合,例如 List
或 ArrayList
(请参阅其他答案)。
关于arrays - Array.Add 与 +=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14620290/