gpt4 book ai didi

PowerShell 逻辑

转载 作者:行者123 更新时间:2023-12-03 14:36:49 29 4
gpt4 key购买 nike

望着help section about_Comparison_Operators of PowerShell我是这样理解的:

PS C:\> $false,$false -eq $true
PS C:\>

左边的没有匹配右边的所以没有返回任何东西甚至不是 $null .

我不明白这个:
PS C:\> $true -eq $false,$false
True
PS C:\>

是不是因为它是第一次做 $true -eq $false返回 错误 ,然后把那个 错误 和做 $false -eq $false返回 ?

更多信息

下面返回 false 的原因是因为它将字符串与数组进行比较,对吗?字符串不等于数组。
PS C:\> "abc" -eq "abc","def"
False

回答?

更多挖掘表明 $true等于一个对象。
PS C:\> $true -eq [array]
True
PS C:\> $true -eq [string]
True
PS C:\> $true -eq [int]
True
PS C:\> $true -eq [bool]
True

重要的是这些对象的值。
PS C:\> $true -eq [int]0
False

最佳答案

我喜欢像这样的关于语言行为和特性的基本问题......给我一个阅读 PowerShell 语言规范的借口。

您可以下载上述规范:2.03.0 .请参阅第 7.8.1 节 - 相等和关系运算符。

对于问题的第一部分,实际上返回了一个空数组,说明如下:($false,$false -eq $true).psbase

Length         : 0
LongLength : 0
Rank : 1
SyncRoot : {}
IsReadOnly : False
IsFixedSize : True
IsSynchronized : False
Count : 0

从规范 -

If the value designated by the left operand is not a collection, the result has type bool. Otherwise, the result is a possibly empty unconstrained 1-dimensional array containing the elements of the collection that test True when compared to the value designated by the right operand.



对于第二部分,因为左操作数本身就是一个 bool 值,我认为它总是结果。只有当正确的操作数是一个集合时。

一些例子:
$true -eq 1,2,3,4
$true -eq '','','',''
$true -eq '',1,$true,$false
$true -eq $null,$false,1,''

所有这些都返回 $true .相反,所有这些都返回 $false
$false -eq 1,2,3,4
$false -eq '','','',''
$false -eq '',1,$true,$false
$false -eq $null,$false,1,''
$false -eq $true,$true,$true

左操作数的类型非常重要。这将返回 $true : $false -eq 0因为右操作数可以转换为左操作数的类型。

关于PowerShell 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15912721/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com