为什么'$true -eq“字符串"'返回 $true? [英] Why does '$true -eq "string"' returns $true?
问题描述
在 powerShell 中,您使用-eq"运算符将布尔值与字符串进行比较,它总是会返回与我之前比较时相同的布尔值.
In powerShell you compare a boolean with a string with the "-eq" operator it will always return the same boolean as I used to compare.
例如
$shouldBeFalse = $true -eq "hello"
$shouldBeTrue = $false -eq "hello"
变量 $shouldBeFalse 是 $true.变量 $shouldBeTrue 是 $false.
The variable $shouldBeFalse is $true. The variable $shouldBeTrue is $false.
我不得不使用Equals"方法:
I had to use the "Equals" method:
$shouldBeFalse = $true.Equals("hello")
在这种情况下,$shouldBeFalse 是 $false.
In this case $shouldBeFalse is $false.
但是为什么会返回带有布尔值的 -eq 运算符呢?
But why returns the -eq operator with boolean these kind of results?
推荐答案
PowerShell 将始终使用左侧参数的类型进行评估.由于左侧有一个布尔值,PowerShell 将尝试将Hello"转换为布尔值,以便使用 -eq
进行评估.
PowerShell will always evaluate using the type of the left-side argument. Since you have a boolean on the left PowerShell will try and cast "Hello" as a boolean for the purpose of evaluating with -eq
.
因此,在您的情况下, "hello"
被转换为布尔值 [bool]"hello"
,因为它不是零长度字符串,所以它的计算结果为 True.如果你反其道而行之,你会看到类似的行为.
So in your case "hello"
is converted to a boolean value [bool]"hello"
which would evaluate to True since it is not a zero length string. You would see similar behavior if you did the opposite.
PS C:> "hello" -eq $true
False
PS C:> [bool]"hello" -eq $true
True
在第一种情况下,$true
被转换为字符串true",它不等于hello",因此为 false.在第二种情况下,我们将hello"转换为布尔值,因此 -eq
将比较布尔值.由于提到的原因,这评估为 True.
In the first case $true
is converted to a string "true" which does not equal "hello" hence false. In the second case we cast "hello" to boolean so the -eq
will compare boolean values. For reasons mentioned about this evaluates to True.
另一个很好的解释来自这个答案,它可能会将您的问题标记为重复:为什么是 $false -eq """真的吗?
Another good explanation comes from this answer which might get your question flagged as a duplicate: Why is $false -eq "" true?
这篇关于为什么'$true -eq“字符串"'返回 $true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!