You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中如何切换System.Collections.Generic.Dictionary的布尔值范围

泛型字典多键布尔值批量操作方案

批量统一赋值

如果需要给多个指定键设置相同值,直接遍历键列表逐个赋值即可,示例:

# 给0,0、0,1、0,2三个坐标统一设为$true
'0,0', '0,1', '0,2' | ForEach-Object { $Grid[$_] = $true }

批量布尔值翻转(True/False互转)

要实现指定键值的批量切换,遍历过程中读取当前值取反后重新赋值即可,示例:

# 批量翻转0,0、0,1、0,2三个坐标的布尔值
'0,0', '0,1', '0,2' | ForEach-Object { $Grid[$_] = -not $Grid[$_] }

可选:封装为复用函数

如果需要频繁执行批量切换操作,可以封装为自定义函数简化调用:

function Switch-GridBoolValue {
    param(
        [Parameter(Mandatory = $true)]
        [System.Collections.Generic.Dictionary[string, bool]]$TargetGrid,
        [Parameter(Mandatory = $true)]
        [string[]]$CoordinateKeys
    )
    $CoordinateKeys | ForEach-Object {
        $TargetGrid[$_] = -not $TargetGrid[$_]
    }
}

# 调用示例
Switch-GridBoolValue -TargetGrid $Grid -CoordinateKeys '0,0', '0,1', '0,2'

内容的提问来源于stack exchange,提问作者BaBa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:06:06