【问题标题】:Cannot pass hashtable as a function parameter [duplicate]无法将哈希表作为函数参数传递[重复]
【发布时间】:2021-03-04 20:11:23
【问题描述】:

在下面的代码中,我试图将哈希表传递给函数,但它总是将其类型更改为 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

我在问看的方向。我的代码有什么问题?

【问题讨论】:

    标签: powershell


    【解决方案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

    【讨论】:

    • 是的,遗憾的是 PowerShell 没有阻止分配给应该是只读的自动变量 - 有关背景信息,请参阅 this answer
    猜你喜欢
    • 2014-03-07
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多