list - powershell列表列表:条目初始化由地址而不是值完成

标签 list powershell

我有一个列表,其中每个条目本身就是一个(字符串)列表。

但是,当我将列表分配给“列表列表”条目时,该分配似乎是通过引用而不是通过值来完成的。也就是说,如果基础列表更改,则“列表列表”也会更改。

下面的代码显示了该问题:

$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),另一个包含stringstrings([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/

相关文章:

powershell - 可以在 powershell 脚本上设置最大内存消耗(以%或兆字节为单位)吗?

regex - Powershell特定字符与功能不匹配

powershell - New-ScheduledTaskTrigger -AtLogon重复

python - 更多 'Pythonic' alternate list shuffle 方式

c# - List<T>.InsertRange() 或设计决策中的错误?

Java - 不同的对象列表

c# - 如何使用修剪功能修剪列表内部

java - 我的递归列表的前置功能创建了一个无限列表

powershell - 使用 powershell_script 自动导入 mediawiki

linux - 计算PowerShell中的字符,单词和行数