我正在通过编写一个简单的解析器来自学 PowerShell。我使用 .Net 框架类Collections.Stack
。我想修改堆栈顶部的对象。
我知道我可以pop()
关闭对象,修改它,然后push()
重新打开它,但这让我觉得不雅。
首先,我试过这个:
$stk = new-object Collections.Stack
$stk.push( (,'My first value') )
( $stk.peek() ) += ,'| My second value'
这引发了一个错误:
Assignment failed because [System.Collections.Stack] doesn't contain a settable property 'peek()'.
At C:\Development\StackOverflow\PowerShell-Stacks\test.ps1:3 char:12
+ ( $stk.peek <<<< () ) += ,'| My second value'
+ CategoryInfo : InvalidOperation: (peek:String) [], RuntimeException
+ FullyQualifiedErrorId : ParameterizedPropertyAssignmentFailed
接下来我尝试了这个:
$ary = $stk.peek()
$ary += ,'| My second value'
write-host "Array is: $ary"
write-host "Stack top is: $($stk.peek())"
这防止了错误,但仍然没有做正确的事情:
Array is: My first value | My second value
Stack top is: My first value
显然,分配给 $ary 的是堆栈顶部对象的副本,所以当我在 $ary 中的对象时,堆栈顶部的对象保持不变。
最后,我阅读了 [ref] 类型,并尝试了这个:
$ary_ref = [ref]$stk.peek()
$ary_ref.value += ,'| My second value'
write-host "Referenced array is: $($ary_ref.value)"
write-host "Stack top is still: $($stk.peek())"
但仍然没有骰子:
Referenced array is: My first value | My second value
Stack top is still: My first value
我假设该peek()
方法返回对实际对象的引用,而不是克隆。如果是这样,那么引用似乎被 PowerShell 的表达式处理逻辑的克隆替换。
有人可以告诉我是否有办法做我想做的事?还是我必须恢复到pop()
/ 修改 / push()
?