我有一个列表,其中每个条目本身就是一个(字符串)列表。
但是,当我将列表分配给“列表列表”条目时,该分配似乎是通过引用而不是通过值来完成的。也就是说,如果基础列表更改,则“列表列表”也会更改。
下面的代码显示了该问题:
$work=New-Object "System.Collections.Generic.List[String]"
$group=New-Object "System.Collections.Generic.List[System.Collections.Generic.List[String]]"
$work.Add("One")
$work.Add("Two")
$group.Add($work)
write-host "-->First Add"
foreach ($g in $group) {
write-host "--Entry"
foreach ($ge in $g) {
write-host $ge
}
}
$work.Clear()
$work.Add("OneOne")
$work.Add("TwoTwo")
$group.Add($work)
write-host "-->Second Add"
foreach ($g in $group) {
write-host "--Entry"
foreach ($ge in $g) {
write-host $ge
}
}
我得到以下输出:
-->First Add
--Entry
One
Two
-->Second Add
--Entry
OneOne
TwoTwo
--Entry
OneOne
TwoTwo
我期望这样:
-->First Add
--Entry
One
Two
-->Second Add
--Entry
One
Two
--Entry
OneOne
TwoTwo
抱歉,如果这个查询看起来很混乱,但是我很难描述这个问题。
我怎样才能解决这个问题?
最佳答案
奇怪的是,这似乎可行...
$work = New-Object System.Collections.Generic.List[String]
$group = New-Object System.Collections.Generic.List[[String[]]]
我得到了预期的输出
-->First Add
--Entry
One
Two
-->Second Add
--Entry
One
Two
--Entry
OneOne
TwoTwo
在两种情况下,它们看起来都是相同的
type
PS C:\> $group=New-Object "System.Collections.Generic.List[System.Collections.Generic.List[String]]"
PS C:\> $group.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True List`1 System.Object
PS C:\> $group2=New-Object "System.Collections.Generic.List[[String[]]]"
PS C:\> $group2.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True List`1 System.Object
仔细研究一下,一个包含一个通用列表(
List'1
),另一个包含string
的strings
([string[]]
)PS C:\> $group.gettype() | select -ExpandProperty GenericTypeArguments
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True List`1 System.Object
PS C:\> $group2.gettype() | select -ExpandProperty GenericTypeArguments
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String[] System.Array
关于list - powershell列表列表:条目初始化由地址而不是值完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46942910/