gpt4 book ai didi

powershell - 如果键不存在,如何使哈希表抛出错误?

转载 作者:行者123 更新时间:2023-12-02 23:06:47 26 4
gpt4 key购买 nike

使用 Powershell 5,我想避免哈希表在 key 不存在时返回 $null。相反,我想抛出一个异常(exception)。

要清楚:

$myht = @{}

$myht.Add("a", 1)
$myht.Add("b", 2)
$myht.Add("c", $null)

$myht["a"] # should return 1
$myht["b"] # should return 2
$myht["c"] # should return $null
$myht["d"] # should throw an exception


a, b, c 都可以。

d 不是。它不会检测丢失的 key 并返回 $null。我希望抛出异常,因为我的业务案例允许 $null,但不允许未知值。

作为解决方法,我尝试了 .Net 通用字典:

$myht = New-Object "System.Collections.Generic.Dictionary[string, System.Nullable[int]]"

但是,它的行为类似于 powershell 哈希表。

至少,我发现的唯一选择是将测试包装在一个函数中:

function Get-DictionaryStrict{
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Hashtable]$Hashtable,
[Parameter(Mandatory=$true, Position=1)]
[string]$Key
)
if($Hashtable.ContainsKey($Key)) {
$Hashtable[$Key]
}
else{
throw "Missing value"
}
}

$myht = @{ a = 1; b = 2; c = $null }

Get-DictionaryStrict $myht a
Get-DictionaryStrict $myht b
Get-DictionaryStrict $myht c
Get-DictionaryStrict $myht d


它按我想要的方式工作,但语法更冗长,尤其是当对函数的调用发生在其他复杂方法中时。

有没有更简单的方法?

最佳答案

使用 Dictionary<TKey,TValue>改为输入:

$dict = [System.Collections.Generic.Dictionary[string,object]]::new()
$dict.Add('a',$something)
$dict.Add('b',$null)

$dict.Item('a') # returns value of `$something`
$dict.Item('b') # returns `$null`
$dict.Item('c') # throws

关于powershell - 如果键不存在,如何使哈希表抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62174693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com