如何将有序哈希表传递给函数?
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,ParameterSetName='Hashtable')] [hashtable]$Hashtable ) if($PSCmdlet.ParameterSetName -eq 'Hashtable'){ $OrderedHashtable = $Hashtable } $OrderedHashtable }