我不明白为什么按 Enter 键和按键盘上的 0 是一样的。
[int] $Choice = -1
$Count = 2
while ($Choice -lt 0 -or $Choice -gt $Count)
{
Write-Host "Input number"
$Choice = Read-Host
Write-Host "choice:"
Write-Host $Choice
}
即使直接按回车,输出也将是 0。我希望用户明确输入 0。
最佳答案
在第一个声明中:
[int] $Choice = -1
...您将 $choice
类型转换为 [int]
。
当您将强制转换应用于赋值的左侧(变量名称的左侧)时,PowerShell 会将其“记住”为类型约束,并将该变量视为强类型 - PowerShell 将尝试将您分配给 $choice
的任何内容从那里转换为 [int]
。
在没有任何其他输入的情况下按提示符中的 Enter 会导致 Read-Host
返回空字符串(如 ""
)
转换逻辑将空字符串视为 $null
,并将 $null
转换为 [int]
得到值 0
。您可以通过直接将空字符串转换为 [int]
来看到这一点:
PS C:\> [int]""
0
如果您明确需要一个数字,您可能应该在分配给 $Choice
之前验证来自 Read-Host
的输入:
$inputString = Read-Host
if($inputString -notmatch '^\d+$') {
Write-Host "Digits only please!"
continue
}
关于powershell - 为什么按 "Enter"相当于数字0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60249679/