为什么 $false -eq “"真的? [英] Why is $false -eq "" true?

查看:50
本文介绍了为什么 $false -eq “"真的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段输出为真:

$x = ($false -eq "") 
Write-Host $x

$x = ($false -eq 0) 
Write-Host $x

既然 $false 和 "" 是不同的数据类型,它不应该自动等于 false 吗?

Since $false and "" are different data types, shouldn't it automatically equal false?

推荐答案

在进行比较操作时,PowerShell 会自动尝试强制运算符右侧的对象与左侧的类型匹配.

When doing comparison operations, PowerShell will automatically attempt to coerce the object on the right-hand side of the operator to match the type on the left-hand side.

在将 [string] 强制转换为 [bool] 的情况下,任何非空字符串将评估为 $true,并且空字符串将评估为 $false.请参阅博客文章Boolean值和运算符,了解有关将不同数据类型自动转换为布尔值的更多信息.

In the case of coercing [string] to [bool], any non-null string will evaluate as $true, and a null string will evaluate as $false. See blog post Boolean Values and Operators for more information about automatic conversion of different data types to boolean values.

这有时会导致意想不到的结果:

This sometimes leads to unexpected results:

PS C:\> [bool]"$false" 

True

$false 的字符串值为 'False',这是一个非空字符串,当转换回 [bool] 时计算为 $true.

The string value of $false is 'False', which is a non-null string and evaluated to $true when cast back to [bool].

当操作数具有不同的数据类型时,它还使比较操作不可交换:

It also makes comparison operations non-commutative when the operands are of different data types:

PS C:\> '' -eq $false
False
PS C:\> $false -eq ''
True

在第一次比较中,值 $false 被自动转换为字符串以匹配第一个操作数 ('') 的类型,因此您'重新实际比较 '' -eq 'False',其计算结果为 $false.

In the first comparison the value $false is auto-cast to a string in order to match the type of the first operand (''), so you're actually comparing '' -eq 'False', which evaluates to $false.

在第二次比较中,字符串 '' 被自动转换为布尔值,同样是为了匹配第一个操作数的类型 ($false),所以这次您实际上是在比较 $false -eq $false,其计算结果为 $true.

In the second comparison the string '' is auto-cast to a boolean, again in order to match the type of the first operand ($false), so this time you're actually comparing $false -eq $false, which evaluates to $true.

这篇关于为什么 $false -eq “"真的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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