所以,我正在尝试创建一个可用于数据导航的树型变量.尝试在PowerShell中的哈希表上使用引用变量时,我遇到了一个问题.请考虑以下代码:
$Tree = @{ TextValue = "main"; Children = @() }
$Item = @{ TextValue = "sub"; Children = @() }
$Pointer = [ref] $Tree.Children
$Pointer.Value += $Item
$Tree
Run Code Online (Sandbox Code Playgroud)
检查引用变量时$Pointer,它显示适当的值,但主变量$Tree不受影响.有没有办法在PowerShell中创建对哈希表元素的引用,我将不得不切换到二维数组?
编辑更多信息:
我接受了Mathias的回答,因为使用List看起来就像我需要的那样,但是对于数组和引用如何交互需要更多的清晰度.试试这段代码:
$Tree1 = @()
$Pointer = $Tree1
$Pointer += 1
Write-Host "tree1 is " $Tree1
$Tree2 = @()
$Pointer = [ref] $Tree2
$Pointer.Value += 1
Write-Host "tree2 is " $Tree2
Run Code Online (Sandbox Code Playgroud)
从输出中可以看出,可以获得对数组的引用,然后通过该引用修改数组的大小.我认为如果数组是另一个数组或哈希表的元素,它也会有效,但事实并非如此.PowerShell似乎处理不同的方式.