powershell - 如何检查 PowerShell 变量是否是有序哈希表?
问题描述
在 PowerShell 中,如何检查变量是否为哈希表,是否已排序?
在第一个例子中,我正在测试一个有序的哈希表是否是 type Hashtable
,但似乎不是。
在此之后,我使用 . 检查了变量类型GetType()
。这似乎表明有序哈希表是 type OrderedDictionary
。
最后,我测试了一个有序的哈希表是否是 type OrderedDictionary
,但这会导致错误。
我认为必须有办法做到这一点?
Hashtable
仅检查
$standard = @{}
$ordered = [ordered]@{}
if ($standard -is [Hashtable]) { Write-Output "True" } else { Write-Output "False" }
if ($ordered -is [Hashtable]) { Write-Output "True" } else { Write-Output "False" }
真假
_
获取普通和有序哈希表的变量类型
查看变量的类型,我可以看到它$ordered
似乎是一种不同的类型,称为OrderedDictionary
.
$standard = @{}
$ordered = [ordered]@{}
Write-Output $standard.GetType()
Write-Output $ordered.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
True True OrderedDictionary System.Object
检查Hashtable
或OrderedDictionary
但是,当我检查变量是否为 typeOrderedDictionary
时,我会收到一条错误消息,指出无法找到该类型。
$standard = @{}
$ordered = [ordered]@{}
if (($standard -is [Hashtable]) -or ($standard -is [OrderedDictionary])) { Write-Output "True" } else { Write-Output "False" }
if (($ordered -is [Hashtable]) -or ($ordered -is [OrderedDictionary])) { Write-Output "True" } else { Write-Output "False" }
True
无法找到类型 [OrderedDictionary]。
解决方案
正如评论中所指出的,完整的命名空间限定类型名称是:
[System.Collections.Specialized.OrderedDictionary]
如果您想接受这两种类型,例如作为函数中的参数参数,请使用它们的公共接口IDictionary
:
function Test-IsOrdered
{
param(
[System.Collections.IDictionary]
$Dictionary
)
$Dictionary -is [System.Collections.Specialized.OrderedDictionary]
}
Test-IsOrdered
现在将接受任何字典类型,包括常规[hashtable]
: Test-IsOrdered @{}
,但只会Test-IsOrdered ([ordered]@{})
返回$true
推荐阅读
- python - 如何在 django 中处理 ModelChoiceField 表单的发布请求?属性错误?
- excel - 我的“兼容性错误”来自哪里?
- c - 理解格式字符串利用的困难
- asp.net - ASP.NET 会话在导航到另一个站点并返回时不会持续存在?
- ios - 无效的 Swift 支持使用最新的 GM
- typescript - 为什么无效的合并运算符在打字稿中不能用作类型保护?
- python - 如何在 Python 中使用 selenium 单击文本框并输入文本?
- python - 如何在 Mac 上安装 tkinter for Python?
- python - 在 Python 中使用 for 将浮点数附加到列表中
- javascript - Javascript 仅在 IOS 浏览器中返回 NaN