复杂字典的foreach循环不正确

byc*_*nce 5 .net powershell dictionary loops

我正在使用Windows 7和PowerGUI脚本编辑器来编写ps1.这是我的代码的一部分:

#In global scope
$Type_Trans = "System.Collections.Generic.Dictionary[System.String,PSObject]"
$Type_Farms = "System.Collections.Generic.Dictionary[System.Int32,$Type_Trans]"

$Dic_Counts = New-Object $Type_Farms

#...puts some data in $Dic_Counts here...
#It is no problem with printing out it in console

#Now call the function below
Write-Data $Dic_Counts

Function Write-Data
{
    param(
        $Dic_Counts
    )

    Foreach($Dic_CountsSingle in $Dic_Counts)
    {
        Write-DataSingle $Dic_CountsSingle  #THIS LINE!
    }
}
Run Code Online (Sandbox Code Playgroud)

这里很奇怪:为什么Dic_CountsSingle不是KeyValuePair,但是和Dic_Counts?? 一样?

非常感谢你!

Joe*_*oey 11

使用

foreach ($Dic_CountsSingle in $DicCounts.GetEnumerator())
Run Code Online (Sandbox Code Playgroud)

PowerShell中的哈希表也是如此,所以并不特别令人惊讶.


man*_*lds 8

我是这样做的:

$Dic_Counts.keys | %{ $Dic_Counts[$_]  }
Run Code Online (Sandbox Code Playgroud)

  • @bychance它是foreach-object的别名 (2认同)