将索引传递给powershell中的函数

将索引传递给powershell中的函数,powershell,Powershell,在foreach内部的powershell中,我生成了一些按钮,每个按钮都应该调用一个函数,并将其索引作为参数传递,但似乎无法将索引传递给该函数 $RacesButtons = @() for( $i=0; $i -lt $numRaces; $i++ ){ $button = New-Object System.Windows.Forms.Button $RacesButtons = $RacesButtons + $button $RacesButtons[$i].T

在foreach内部的powershell中,我生成了一些按钮,每个按钮都应该调用一个函数,并将其索引作为参数传递,但似乎无法将索引传递给该函数

$RacesButtons = @()
for( $i=0; $i -lt $numRaces; $i++ ){
    $button = New-Object System.Windows.Forms.Button
    $RacesButtons = $RacesButtons + $button
    $RacesButtons[$i].Text = "$($RacesFiles[$i])"
    $RacesButtons[$i].Add_Click({NewNpc $i})
    $Form.Controls.Add($RacesButtons[$i])
}
它应该传递0到8($numRaces是9),但是它传递null,我收到这个错误

Indexing operation failed. The index value of the matrix is null.
 In C:\Users\Marco\Desktop\Music&Npc\Music&Npc.ps1:137 car:2
+     $NpcDetailsTextBox.Text = $RacesFiles[$race]
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArrayIndex
“NpcDetailsTextBox”是一个文本框,“RacesFiles”是一个数组。 奇怪的是,每个按钮的文本(设置为$RacesButtons[$i].text=“$($RacesFiles[$i])”在设置添加按钮之前)都是正确的

我收到了与此相同的错误

$RacesButtons[$i].Add_Click({NewNpc $($i)})
但是如果我用其中一个

$RacesButtons[$i].Add_Click({NewNpc "$i"})
$RacesButtons[$i].Add_Click({NewNpc "$($i)"})
它不会返回错误,但每个按钮都会将0传递给函数

$RacesButtons = @()
for( $i=0; $i -lt $numRaces; $i++ ){
    $button = New-Object System.Windows.Forms.Button
    $RacesButtons = $RacesButtons + $button
    $RacesButtons[$i].Text = "$($RacesFiles[$i])"
    $RacesButtons[$i].Add_Click({NewNpc $i})
    $Form.Controls.Add($RacesButtons[$i])
}
有没有办法解决这个问题?
提前感谢

这样做的原因是在
Add\u Click
的脚本块中,
$i
变量未知($null)。 在这种情况下,我会寻求一个简单的解决方案,并使用按钮自己的
标记
属性来保存
$I的当前值

$RacesButtons = for( $i = 0; $i -lt $numRaces; $i++ ){
    $button = New-Object System.Windows.Forms.Button
    $button.Text = "$($RacesFiles[$i])"
    # store the value of $i in the button's Tag property so it will be kept
    $button.Tag  = $i
    $button.Add_Click({ NewNpc $this.Tag })
    $Form.Controls.Add($button)
    # output the new button so it gets collected in the $RacesButtons array
    $button
}

希望这有帮助

它能工作!谢谢但是我对你说的第二条评论有一个问题,你说要将按钮添加到数组中,我应该用“$button”输出它,但是我在创建后立即用“$RacesButtons=$RacesButtons+$button”添加到数组中,是不是一样?(它的工作原理与我的相同,但可能有问题)@MarcoF
$RacesButtons=$RacesButtons+$button
也会给出相同的结果。不同之处在于,当向这样的数组中添加项时,实际上每次迭代都在重新创建整个数组,这会耗费时间和内存。当然,在一个小数组上,您不会注意到这一点,但是测试表明,使用(…)的
$RacesButtons=for(…)
收集数组要快得多。