arrays - Array.Add 与 +=

标签 arrays powershell

我在 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

如果不可能,请考虑使用更高效的集合,例如 ListArrayList(请参阅其他答案)。

关于arrays - Array.Add 与 +=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14620290/

相关文章:

java - 数组查找与位移位的性能

javascript - 在 JavaScript 中查找多维数组中最长的字符串

powershell - 将透明png转换为jpg powershell

powershell - 不包含分割方法

powershell - ErrorAction默认在PowerShell脚本中停止

python - 如何将 ndarray 转换为 scipy 中的矩阵?

c - C 中两个数组元素地址之间的偏移量

arrays - 在字典中添加键值对 swift

powershell - echo "string"> Windows PowerShell 中的文件将不可打印的字符附加到文件

bash - powershell bash 循环随机卡住等待键盘输入