powershell - 如果键不存在,如何使哈希表抛出错误?
问题描述
使用 Powershell 5,我想避免$null
在密钥不存在时返回哈希表。相反,我想抛出一个例外。
要清楚:
$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
不是。它不会检测到丢失的密钥并返回$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
它按我想要的方式工作,但语法更冗长,特别是当对函数的调用发生在其他复杂方法中时。
有没有更简单的方法?
解决方案
您可以使用其他集合类型,但也可以使用严格模式
Set-StrictMode -Version '2.0'
$x=@{a=5;b=10}
$x.a
$x.c
你得到一个错误:
在此对象上找不到属性“c”。验证该属性是否存在。
请注意不要破坏工作脚本,因为严格模式会强制执行许多其他内容,而不是不存在属性的错误,例如使用不存在的变量或超出范围的索引时出错。这取决于您在版本中使用的级别。
推荐阅读
- c++ - 如何在类中安全地访问 const 共享数组
- aerospike - 是否可以在 Aerospike 中使用主键和辅助键来获取记录?
- python - 关于如何访问函数返回的简单问题
- microsoft-graph-api - MS Graph - 如何在我的 DC 下列出来自特定 OU 的所有用户?
- python - 深度学习:当学习率太高时
- java - apk 文件调试 - React Native
- python - 金字塔中的随机无交易
- c++ - 为什么在使用 const 函数 C++ 时 const 是多余的?
- python - 来自 (BLS)API 的多个数据源/系列请求仅使用 URL
- angular - 如何使这个响应和每个框填充到图像框?