OutputType 屬性如何作業?
function test
{
[OutputType([Bool])]
Param ($a)
return $a
}
$one = test 1
$two = test 0
$one.GetType() # Int32
$two.GetType() # Int32
我預計 $one 是真的,$two 是假的。
uj5u.com熱心網友回復:
以Abraham Zinala和Mike Shepard的有益評論為基礎:
正如概念about_Functions_OutputTypeAttribute幫助主題所示:
該
[OutputType()]屬性不控制函式或腳本的實際輸出資料型別。PowerShell無法像 C# 等語言那樣宣告強制的“回傳型別”:雖然約束和記錄函式或腳本的輸出(“回傳”)是有意義的,但在技術上可以自由輸出任意數量的物件,任何型別,只需寫入成功輸出流。
相比之下,您可以強制提供給函式或腳本的輸入資料型別,即通過型別約束其引數定義;例如,您可以確保傳遞給您的引數的
-a引數是布林值,通過替換param($a)為param([bool] $a),正如 Abraham 所指出的 - 請參閱概念about_Functions_Advanced_Parameters幫助主題。
相反,該
[OutputType()]屬性僅具有資訊字符:它將元資料添加到列出輸出型別的函式定義中,PowerShell 的幫助系統和制表符補全等功能可以利用這些功能。
由函式/腳本作者確保列出的型別
[OutputType()]反映了實際的輸出資料型別。- 因此,資訊可能不正確 - 就像您的情況一樣,是偶然的。
因此,您的函式需要確保將所需的資料型別作為輸出陳述句的一部分輸出:
function test
{
[OutputType([bool])]
Param ($a) # $a is allowed to be of any type (no type constraint present)
# Output a [bool] explicitly.
# Note: No strict need for `return` here,
# thanks to PowerShell's implicit output behavior.
[bool] $a
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/466235.html
標籤:电源外壳
