我撰寫了以下函式將字串拆分為字串陣列。在某些情況下,輸入是 $null,在這種情況下函式應該回傳 $null,或者當輸入已經是字串陣列時,在這種情況下輸入應該按原樣回傳。
function Split-Tests($tests)
{
if ($tests -eq $null)
{
return $tests
}
if (($tests.GetType() -eq [string[]]) -and $tests.Count -ne 1)
{
return $tests
}
return ([string]$tests).Split(",")
}
該函式應回傳 $null 或字串數??組。但是,當我像這樣呼叫這個函式時Split-Tests "1,2,3",即使 string.Split 函式回傳 string[],回傳值的型別也是 object[]。
我嘗試了對 string[] ( return [string[]](([string]$tests).Split(","))) 的顯式強制轉換,并嘗試了該[OutputType([string[]])]屬性,但回傳型別仍為 object[]。
作為最后的手段,我將函式呼叫的結果轉換為 [string[]]。那行得通,但我寧愿在函式外部定義回傳型別。你能幫助我嗎?
編輯:我發現這個答案表明我可以在“return”和回傳值之間添加一個逗號。不幸的是,就我而言,它沒有幫助。甚至此回復中提到的“寫入輸出”也沒有進行更改。
再次編輯:逗號技巧做到了,我第一次嘗試時一定做錯了什么。
uj5u.com熱心網友回復:
這是正常行為。與其他編程語言不同,PowerShell展開陣列并將它們逐個元素地輸出到管道,作為流。甚至returnPowerShell 中的陳述句實際上也不會按原樣回傳給定物件,但也會輸出到管道。
IE。
return ([string]$tests).Split(",")
只是一個捷徑:
([string]$tests).Split(",") # Output to the pipeline
return # Return from the function
當輸出被捕獲到一個變數中時,PowerShell 只會看到傳遞給管道的各個元素。它不知道原始陣列型別。由于管道中的值可能是不同的型別,它只能創建一個通用object[]陣列,它接受任何元素型別。
Function Fun { return 1,2,3,'a','b','c' }
$x = Fun # Now x contains 3 ints and 3 strings.
要強制輸出string[]陣列,可以在陣列前面使用一元形式的逗號運算子來防止列舉:
function Split-Tests( $tests)
{
if ($tests -eq $null)
{
return $tests
}
if (($tests.GetType() -eq [string[]]) -and $tests.Count -ne 1)
{
return ,$tests
}
,([string]$tests).Split(",") # No return statement needed here
}
$a = Split-Tests "1,2,3"
$a.GetType().Name # Outputs "String[]"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/496651.html
標籤:电源外壳
上一篇:如何只讀取xml屬性的第一葉
