我不太确定这个确切的问题是否重复,但我在 stackoverflow 上找不到我的具体问题,所以我猜不是.
I'm not quite sure if this exact question is a duplicate, but I couldn't find my specific question on stackoverflow, so I guess it's not.
$true 是一个布尔类型:
($true).getType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Boolean System.ValueType'true' 是一个字符串:
('true').gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object为什么这个条件成立?
PS C:\WINDOWS\system32> if ('True' -eq $true) {'yes'} else {'no'} yes仅仅因为字符串被称为 True 就像布尔值 true 一样?如果我将它与任何其他字符串进行比较,则会得到不同的结果:
only because the string is called True just like the boolean true? If I compare it with any other string, there is a different outcome:
PS C:\WINDOWS\system32> 'hello' -eq $true False PS C:\WINDOWS\system32> 'true' -eq $true True如果你在 C# 中执行 'true' == true 它会打印一个 cannot convert string to bool 错误并且 C# 和 PS 都基于 并且有相当相同的语法.为什么会有不同的结果?这对我来说似乎很奇怪.
if you do 'true' == true in C# it prints an cannot convert string to bool error and both C# and PS are based on and have quite the same syntax. why is there a different outcome? this seems very strange to me.
PowerShell 如何将 'true' 评估为 $true?
How is PowerShell evaluating 'true' to $true?
推荐答案在 PowerShell 中,运算符重载由左侧 (lhs) 参数决定.
In PowerShell, operator overloading is determined by the left-hand side (lhs) argument.
这意味着当您提供字符串作为 lhs 参数时,解析器将尝试将右侧 (rhs) 也转换为字符串.
This means that when you supply a string as the lhs argument, the parser will attempt to convert the right-hand side (rhs) to a string as well.
当转换为字符串时,$true 以字符串True"的形式出现 - 由于 PowerShell 的字符串比较运算符在默认情况下都不区分大小写,因此恰好等于true".
When cast to a string, $true comes out as the string "True" - which, since PowerShell's string comparison operators are all case-insensitive by default, happens to equal "true".
这个操作:
'true' -eq $true被解释为
'true' -eq 'True'恰好是 $true,满足您的 if 条件.
Which happens to be $true, satisfying your if condition.
使用 $true,这也恰好相反,因为非空字符串在转换为布尔值时,计算结果为 $true:
With $true, this also happens to work the other way around, because a non-empty string, when converted to a boolean, evaluates to $true:
换句话说
$true -eq 'true'被解释为
$true -eq $true这可能会导致混淆,因为字符串false"会偶然也被评估为$true,仅仅因为字符串false"不为空:
This can lead to confusion, since the string "false" will incidentally also be evaluated as $true, simply because the string "false" is not empty:
PS C:\> $true -eq "true" True PS C:\> $true -eq "false" True PS C:\> $true -eq "" False更多推荐
为什么“真"等于 $true
发布评论