$formFields = @("UserSurname","UserFirstName")
foreach ( $field in $formFields ) {
$($field+"Label") = New-Object system.Windows.Forms.Label
$($field+"Label").Width = 25
}
我正在尝试从一串组件初始化一堆表单项。我只是不明白如何从循环中的另一个值初始化变量。我已经尝试了很多事情,但我认为这段代码最好地说明了我正在尝试做的事情。
似乎无法在循环中构建正确的值
您可以使用
Set-Variable
cmdlet 来执行此操作:
$formFields = @("UserSurname","UserFirstName")
foreach ( $field in $formFields ) {
$label = New-Object system.Windows.Forms.Label
$label.Width = 25
Set-Variable -Name "${field}Label" -Value $label
}
尽管您可能想考虑使用哈希表或其他字典类型:
$formFields = @("UserSurname","UserFirstName")
$formFieldLabels = @{}
foreach ( $field in $formFields ) {
$label = New-Object system.Windows.Forms.Label
$label.Width = 25
$formFieldLabels[$field] = $label
}
现在您可以使用
$formFieldLabels["UserSurname"]
引用标签实例