在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
Run Code Online (Sandbox Code Playgroud)
,(数组构造运算符)的优先级高于* - 请参阅Get-Help about_Operator_Precedence
注意:以下代码段不使用数组子表达式运算符@(...),因为没有必要指定数组文字 - 数组构造运算符,就足够了.
因此,
2*3, 4*5
Run Code Online (Sandbox Code Playgroud)
被解析为:
2 * (3, 4) * 5
Run Code Online (Sandbox Code Playgroud)
和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
Run Code Online (Sandbox Code Playgroud)
虽然我并不真正了解提供,优先级的设计理由而不是运算符,但我想到了*一个可能的原因:
一些PowerShell的运营商-尤其是-replace和-split-采取数组作为他们的RHS.
如果,具有更高的优先级,则可以使用以下表达式,而无需在RHS的元素周围使用括号:
> 'A barl and his money are soon parted.' -replace 'bar', 'foo'
A fool and his money are soon parted.
Run Code Online (Sandbox Code Playgroud)
如果我自己的实际经验是可以接受的,遇到这个优先问题,在这个问题中出乎意料的方式是罕见的.