在下面的代码中,我试图将一个哈希表传递给一个函数,但它总是将其类型更改为 Object[]
function Show-Hashtable{
param(
[Parameter(Mandatory = $true)][Hashtable] $input
)
return 0
}
function Show-HashtableV2{
param(
[Parameter(Mandatory = $true)][ref] $input
)
write-host $input.value.GetType().Name
return 0
}
[Hashtable]$ht=@{}
$ht.add( "key", "val" )
# for test
[int]$x = Show-HashtableV2 ([ref]$ht)
# main issue
[int]$x = Show-Hashtable $ht.clone()
在上面,我尝试使用 $ht.Clone()
而不是 $ht
,但没有成功。
我得到了什么:
Object[]
Show-Hashtable : Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Hashtable".
At C:\_PowerShellRepo\Untitled6.ps1:26 char:11
+ [int]$x = Show-Hashtable $ht #.clone()
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Show-Hashtable], PSInvalidCastException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException,Show-Hashtable
我问的是看的方向。我的代码有什么问题?
答案 0 :(得分:1)
$input
是一个 automatic variable,它包含一个枚举器,用于枚举传递给函数的所有输入。您的参数名称与此冲突(我想知道为什么 PowerShell 在这种情况下不输出警告)。
解决方法很简单,只是给参数命名不同,e。 G。 InputObject
:
function Show-HashtableV2{
param(
[Parameter(Mandatory = $true)][ref] $InputObject
)
write-host $InputObject.value.GetType().Name
return 0
}
现在函数打印 System.Collections.Hashtable
。