为什么'$真当量"串QUOT;'返回$真的吗? [英] Why does '$true -eq "string"' returns $true?

查看:182
本文介绍了为什么'$真当量"串QUOT;'返回$真的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PowerShell中你比较的布尔带的当量操作符的字符串它总是返回相同的布尔为我所用比较。

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.

我不得不使用等于的方法:

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一个布尔值会尝试投你好作为一个布尔与 -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.

所以你的情况你好转换为布尔值 [BOOL]你好这将评估为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

在第一种情况下 $真被转换成不等于你好,因此假的字符串真。在第二种情况下,我们投你好布尔因此 -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当量""真的吗?

Another good explanation comes from this answer which might get your question flagged as a duplicate: Why is $false -eq "" true?

这篇关于为什么'$真当量"串QUOT;'返回$真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆