如何在Powershell中创建数组的空数组?
我想在Powershell中创建一个空数组,以容纳值的元组"(数组是不可变的).
I want to create an empty array of arrays in Powershell to hold "tuples" of values (arrays are immutable).
因此,我尝试以下操作:
Therefore I try something like:
$arr
的类型为Object[]
.我已经读到+= @(1,2)
将给定的元素(即@(1,2)
)附加到$arr
(实际上是创建一个新数组).但是,在这种情况下,数组似乎是串联在一起的,为什么?
The type of $arr
is Object[]
. I've read that += @(1,2)
appends the given element (i.e. @(1,2)
) to $arr
(actually creates a new array). However, in this case it seems that the arrays are concatenated, why?
$arr = @()
$arr += @(1,2)
$arr.Length // 2 (not 1)
如果执行以下操作,则$arr
似乎包含两个数组@(1,2),@(3,4)
,这就是我想要的:
If I do as follows, it seems that $arr
contains the two arrays @(1,2),@(3,4)
, which is what I want:
$arr = @()
$arr += @(1,2),@(3,4)
$arr.Length // 2
如何初始化数组的空数组,以便一次可以添加一个子数组,例如$arr += @(1,2)
?
How do I initialize an empty array of arrays, such that I can add one subarray at a time, like $arr += @(1,2)
?
Bruce Payette的答案将起作用.语法对我来说似乎有点尴尬,但它确实有效.至少不是Perl.
The answer from Bruce Payette will work. The syntax seems a bit awkward to me, but it does work. At least it is not Perl.
执行此操作的另一种方法是使用ArrayList
.对我来说,这种语法更清晰,并且更可能在六个月内被另一个开发人员(或我本人)理解.
Another way to do this would be with an ArrayList
. To me, this syntax is more clear and more likely to be understood by another developer (or myself) in six months.
[System.Collections.ArrayList]$al = @()
$al.Add(@(1,2))
$al.Add(@(3,4))
foreach ($e in $al) {
$e
$e.GetType()
}