怎么投 myChar
在 New-Variable -Name myChar -Value "=" -Option ReadOnly
输入 [char]
,或者(更一般地)我如何指定用 New-Variable
创建的变量的类型?
谢谢
编辑(归功于@veefu):
[char]$sampleVariable="A"
$sampleAttributes=(Get-Variable -Name sampleVariable).Attributes[0]
New-Variable -Name myVariable
(Get-Variable -Name myVariable).Attributes.Add($sampleAttributes)
$myVariable="ab" # GENERATES CONVERSION ERROR (WHICH HELPS A LOT)
$myVariable="a" # DOES NOT GENERATE CONVERSION ERROR (EVERYTHING'S FINE)
编辑(归功于@postanote):
[char]$anyCharacter="A"
# FOLLOWING LINE GENERATES CONVERSION ERROR (GOOD THING)
Set-Variable -Name anyCharacter -Value "ab" -Option ReadOnly
# FOLLOWING LINE DOES NOT GENERATE CONVERSION ERROR (GREAT)
Set-Variable -Name anyCharacter -Value "a" -Option ReadOnly
最佳答案
现在在 PowerShell 中几乎不可能做到这一点,所以我打开了一个问题 You should be able to set the type conversion attribute on a variable with New-Variable来解决这个问题。
关于powershell - 使用 New-Variable 函数创建变量时如何显式声明变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905423/