簡體   English   中英

Powershell功能+字典

[英]powershell function + dictionary

我不了解這種行為:

function foo ($item, $dict_of_item) {
    if ($dict_of_item.keys -contains $item){
        return $dict_of_item[$item] }
    else{
        return $item }       
}

$dict = @{
'a' = 1
'b' = 2
'c' = 3}

foo('a',$dict)
a

Name                           Value                                                                                                                                                                                                                             
----                           -----                                                                                                                                                                                                                             
c                              3                                                                                                                                                                                                                                 
b                              2                                                                                                                                                                                                                                 
a                              1          

我想要char的返回碼,但我不明白為什么我會在輸出中得到字典。

您正在錯誤地調用該函數。 您不必在參數周圍加上括號,而應像命令行參數一樣傳遞它們。 因此,在您的情況下,請更改:

foo('a',$dict)

至:

foo 'a' $dict

或者,更清楚地說:

foo -item 'a' -dict_of_item $dict

PowerShell將('a',$dict)為數組,因此您具有:

$item = ('a',$dict)
$dict_of_item = $null

由於您的測試使用這些參數失敗,因此它將向您返回$item 也就是說,它將返回一個帶有字符和字典的數組,這是您在屏幕上看到的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM