我通过编写一个简单的解析器来教导自己PowerShell。我使用.Net框架类Collections.Stack
。我想修改堆栈顶部的对象。Powershell/.Net:获取对方法返回的对象的引用
我知道我可以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中的对象时,堆栈顶部的对象保持不变。
最后,我上格兰[参考]式阅读起来,并试图这样:
$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()
?