在这种情况下使用New-Object:
PS> $arr = New-Object int[] 10000; $arr.length
10000
或者,在 PSv5+ 中,对类型使用静态 new() 方法:
PS> $arr = [int[]]::new(10000); $arr.length
10000
这些命令创建一个强类型数组,在本例中使用基本类型[int]。
如果用例允许,出于性能和类型安全的原因,这是更可取的。
如果您需要像 PowerShell ([System.Object[]]) 一样创建“无类型”数组,请将 object 替换为 int;例如,[object[]]::new(10000);这样一个数组的元素将默认为$null。
TessellatingHeckler's helpful answer,但是,它显示了一个更简洁的替代方案,甚至允许您将所有元素初始化为特定值。
数组有固定的大小;如果您需要一个可以预分配并动态增长的类数组数据结构,请参阅Bluecakes' helpful [System.Collections.ArrayList]-based answer。
[System.Collections.ArrayList] 是 [System.Object[]] 的可调整大小的类似物,它的 generic 等效 - 就像上面的 [int[]] 示例一样 - 允许您使用特定类型用于性能和稳健性(如果可行),是 [System.Collections.Generic.List[<type>]],例如:
PS> $lst = [System.Collections.Generic.List[int]]::New(10000); $lst.Capacity
10000
请注意 - 与 [System.Collections.ArrayList] 一样 - 指定 初始容量(10000,此处)不会分配具有该大小的内部使用的数组立即 -容量值被简单地存储(并公开为属性.Capacity),当添加第一个元素时,按需分配具有该容量的内部数组(内部大小留有增长空间)到列表中。
[System.Collections.Generic.List[<type>]] 的 .Add() 方法值得称道不 产生输出,而 [System.Collections.ArrayList] 产生输出(它返回刚刚添加的元素的索引)。
# The non-generic ArrayList's .Add() produces (usually undesired) output.
PS> $al = [System.Collections.ArrayList]::new(); $al.Add('first elem')
0 # .Add() outputs the index of the newly added item
# Simplest way to suppress this output:
PS> $null = $al.Add('first elem')
# NO output.
# The generic List[T]'s .Add() does NOT produce output.
PS> $gl = [System.Collections.Generic.List[string]]::new(); $gl.Add('first elem')
# NO output from .Add()