function add($n1, $n2){
return $n1 $n2
}
$num1 = 1
$num2 = 2
$operand = "add"
########################################################################
# Given the above scenario, please try to make the next line work:
# $operand $num1 $num2 -> My ATTEMPT to call function via string variable
add $num1 $num2 # This is what I am trying to achieve with the above line
請演示如何使用字串變數“Operand”呼叫函式。
uj5u.com熱心網友回復:
只要函式已加載到記憶體中,當函式的名稱存盤在變數 ( $operand) 中時,呼叫函式的兩種最常用方法是使用呼叫運算子&:
& $operand $num1 $num2 # => 3
或點源運營商.:
. $operand $num1 $num2 # => 3
您也可以使用Invoke-Expression(即使不推薦),只要將運算式包裝為字串:
Invoke-Expression "$operand $num1 $num2" # => 3
uj5u.com熱心網友回復:
為了補充Santiago Squarzon 的有用答案,這里有一種使用hashtable腳本塊的不同方式:
$funTable = @{
add = { param($n1, $n2) $n1 $n2 }
sub = { param($n1, $n2) $n1 - $n2 }
}
或者,您可以參考函式(之前必須已定義):
$funTable = @{
add = $function:add
sub = $function:sub
}
現在您可以像這樣通過字串變數呼叫函式:
$operand = 'add'
& $funTable.$operand $num1 $num2
# Just a different syntax, it's a matter of taste
$funTable.$operand.Invoke( $num1, $num2 )
您可以使用.代替&,但在大多數情況下不建議這樣做。不同之處在于,.函式定義的任何臨時變數都會泄漏到呼叫者的范圍內,但您通常希望自動洗掉這些變數,這就是這樣&做的。
使用 a 的優點hashtable:
- 運算元函式按邏輯分組。
- 當函式名是用戶輸入時,他們不能運行任意的 PowerShell 代碼(就像使用 一樣
& $operand)。他們只被允許運行你存盤的函式$funTable。否則他們會得到一個錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450533.html
