gpt4 book ai didi

arrays - 为什么表达式需要在数组的括号中

转载 作者:行者123 更新时间:2023-12-05 00:52:26 24 4
gpt4 key购买 nike

在创建 files1 数组中的第二个数组时,数学表达式必须放在括号中。运算符的层次结构在这里不适用吗?

PS C:\src\powershell> Get-Content .\fr-btest2.ps1
$files1 = @(
, @(4, 1024)
, @(2*3, 4*5)
)

$files1
$files1.GetType()
$files1.Length
$files1.Count

'============'

$files2 = @(
, @(4, 1024)
, @((2*3), (4*5))
)

$files2
$files2.GetType()
$files2.Length
$files2.Count
PS C:\src\powershell> .\fr-btest2.ps1
Method invocation failed because [System.Object[]] does not contain a method named 'op_Multiply'.
At C:\src\powershell\fr-btest2.ps1:3 char:5
+ , @(2*3, 4*5)
+ ~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Multiply:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

4
1024

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
2
2
============
4
1024
6
20
True True Object[] System.Array
2
2

最佳答案

, (数组构造运算符)的优先级高于 * - 见 Get-Help about_Operator_Precedence

注意:以下代码片段不使用数组子表达式运算符 @(...) , 因为没有必要指定数组字面量 - 数组构造运算符 ,足够了。

所以,

2*3, 4*5

被解析为:
2 * (3, 4) * 5

并且 PowerShell 不知道如何在 * 的 RHS 上使用数组.

需要使用括号明确优先级: (2*3), (4*5)产生所需的数组, 6, 20 .

顺便说一句:PowerShell 支持 * 的 LHS 上的数组,尽管不是数字意义上的:使用数组作为 LHS(平坦地)复制该数组的频率与(标量,数字)RHS 上指定的一样 - 类似于如何使用 * 复制 LHS 上的字符串:
> (2,3) * 2  # equivalent of: 2, 3, 2, 3
2
3
2
3

优先规则的可能动机

虽然我真的不知道给予 , 的设计原理比 * 等运算符更高的优先级,想到一个可能的原因:

一些 PowerShell 操作符 - 特别是 -replace-split - 将数组作为他们的 RHS。

,具有更高的优先级,可以使用以下表达式,而无需在 RHS 的元素周围使用括号:
> 'A barl and his money are soon parted.' -replace 'bar', 'foo'
A fool and his money are soon parted.

如果我自己的现实世界经验是可以解决的,那么遇到这个优先问题,像这个问题这样意想不到的方式是很少见的。

关于arrays - 为什么表达式需要在数组的括号中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42772642/

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