为什么“真"等于 $true

编程入门 行业动态 更新时间:2024-10-25 07:26:09
本文介绍了为什么“真"等于 $true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不太确定这个确切的问题是否重复,但我在 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

本文发布于:2023-11-24 21:23:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:quot   true

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!