考慮以下:
function GetOneOf($prompt, $values) {
$response=
while ($response -eq $null) {
$response = read-host $prompt
if ( -not ($values -icontains $response)) {
$response = $null
}
}
$response
}
function GetOneOfV2($prompt, $values) {
# "$response=" fragment is missing
while ($response -eq $null) {
$response = read-host $prompt
if ( -not ($values -icontains $response)) {
$response = $null
}
}
$response
}
$resp = GetOneOf 'enter A or B' 'a', 'b'
write-host "RESP: $resp"
$resp = GetOneOfV2 'enter A or B' 'a', 'b'
write-host "RESP: $resp"
為什么GetOneOf不回傳輸入的值并GetOneOfV2回傳它?我看不出有任何理由以這種方式作業。如果第一種情況 ( GetOneOf) 以這種方式作業,因為while構成了另一個范圍并且變數不能在那里更改,那么可以,但是如果是這樣,那么在第二種情況下,應該無法讀取$response回圈外范圍內的值,因為沒有這樣的變數早些時候。事實上,我應該得到no such variable或類似的錯誤。但是,如果我們假設回圈內部的更改在外部可見(第二種情況),并且它們甚至使變數可用于外部作用域,那么第一種情況怎么可能不起作用?
還有我怎樣才能使第一種情況(GetOneOf)起作用?
我使用以下內容:
Name Value
---- -----
PSVersion 5.1.19041.1237
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.19041.1237
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
uj5u.com熱心網友回復:
它與變數范圍無關,您正在分配whileto的回傳值$response,這總是null因為您沒有回傳任何內容。
這應該作業:
function GetOneOf($prompt, $values) {
$response=
while ($response -eq $null) {
$response = read-host $prompt
if ( -not ($values -icontains $response)) {
$response = $null
} else {
echo $response
}
}
$response
}
輸出:
PS C:\> $resp = GetOneOf 'enter A or B' 'a', 'b'
enter A or B: d
enter A or B: f
enter A or B: g
enter A or B: w
enter A or B: a
PS C:\> $resp
a
PS C:\> $resp.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/323315.html
