【问题标题】:foreach loop for a complex dictionary is incorrect复杂字典的 foreach 循环不正确
【发布时间】:2012-04-07 22:57:22
【问题描述】:

我正在使用 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!
    }
}

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

非常感谢!

【问题讨论】:

    标签: .net loops powershell dictionary


    【解决方案1】:

    使用

    foreach ($Dic_CountsSingle in $DicCounts.GetEnumerator())
    

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

    【讨论】:

    • 你能解释这是为什么吗?
    【解决方案2】:

    我认为它在这里崩溃了:

    Foreach($Dic_CountsSingle in $Dic_Counts) 
    

    那个 foreach 循环期望一个数组作为它的第二个参数。 $Dic_Counts 是一个哈希表,所以它没有索引。现在我想知道有序哈希表是否可以在 foreach 循环中工作。它确实有一个索引。

    不。 Foreach 也不会枚举有序哈希表。必须自己做。

    【讨论】:

    • 好吧,我想知道 PowerShell 将自己迭代什么(在foreach 或管道中)。它对System.Collections.Generic.List<T> 这样做,它当然不是一个数组,但它没有任何与数组共同的定义接口,也不是由字典或哈希表实现的。
    【解决方案3】:

    我是这样做的:

    $Dic_Counts.keys | %{ $Dic_Counts[$_]  }
    

    【讨论】:

    • 哇,这是什么语法? “%”?
    • @bychance 它是 foreach-object 的别名
    猜你喜欢
    • 1970-01-01
    • 2015-07-04
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2017-11-24
    • 2015-07-13
    相关资源
    最近更新 更多