本文介绍了将有序哈希表传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将有序哈希表传递给函数?

以下代码引发错误:

function doStuff {
    Param (
        [ordered]$theOrderedHashtable
    )
    $theOrderedHashtable
}

$datFileWithMinSizes  = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847"  }

doStuff -theOrderedHashtable $datFileWithMinSizes

以下内容未保持正确的顺序:

function doStuff {
    Param (
        [Hashtable]$theOrderedHashtable = [ordered]@{}
    )
    $theOrderedHashtable
}

$datFileWithMinSizes  = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847"  }

doStuff -theOrderedHashtable $datFileWithMinSizes

目前我可以使其工作的唯一方法是不按如下方式指定类型,但我想指定类型:

function doStuff {
    Param (
        $theOrderedHashtable
    )
    $theOrderedHashtable
}

$datFileWithMinSizes  = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847"  }

doStuff -theOrderedHashtable $datFileWithMinSizes

推荐答案

使用类型全名:

function Do-Stuff {
    param(
        [System.Collections.Specialized.OrderedDictionary]$OrderedHashtable
    )
    $OrderedHashtable
}

要同时支持常规哈希表和有序字典,使用[System.Collections.IDictionary]接口,如suggested by briantist

function Do-Stuff {
    [CmdletBinding(DefaultParameterSetName='Ordered')]
    param(
        [Parameter(Mandatory=$true,Position=0,ParameterSetName='Ordered')]
        [System.Collections.Specialized.OrderedDictionary]$OrderedHashtable,

        [Parameter(Mandatory=$true,Position=0,ParameterSetName='Hashtable')]
        [hashtable]$Hashtable
    )
    if($PSCmdlet.ParameterSetName -eq 'Hashtable'){
        $OrderedHashtable = $Hashtable
    }
    $OrderedHashtable
}

这篇关于将有序哈希表传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:00