Array.Add vs +=

前端 未结 3 2071
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 19:33

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

3条回答
  •  既然无缘
    2020-11-29 20:05

    If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

    And it's so easy to use.

    Instead of your array declaration, try this:

    $outItems = New-Object System.Collections.Generic.List[System.Object]
    

    Adding items is simple.

    $outItems.Add(1)
    $outItems.Add("hi")
    

    And if you really want an array when you're done, there's a function for that too.

    $outItems.ToArray()
    

提交回复
热议问题