【发布时间】:2016-12-04 20:13:52
【问题描述】:
Powershell 3.0 提供了一种快速创建哈希表的方法,该哈希表还可以保持其顺序,但会消耗少量内存。
问题:
# create ordered hashtable
$a = [ordered]@{}
# populate with 3 key-value pairs
$a['a'] = 15
$a['b'] = 10
$a['c'] = 9
$a
# Name Value
# ---- -----
# a 15
# b 10
# c 9
# get value for key = 'b'
$a['b']
# returns: 10
# get value for indexed last (ordered) item in table: This is desired behaviour
$a[-1]
# returns: 9
# show type of object for variable $a
$a | Get-Member
# returns: TypeName: System.Collections.Specialized.OrderedDictionary
# ...
到目前为止一切都很好。
当将对象序列化到磁盘,然后反序列化时,对象从 System.Collections.Specialized.OrderedDictionary 变为 Deserialized.System.Collections.Specialized.OrderedDictionary。
# serialize to disk
$a | Export-CliXml ./serialized.xml
# deserialize from disk
$d = Import-CliXml ./serialized.xml
# show datatype of deserialized object
# returns: Deserialized.System.Collections.Specialized.OrderedDictionary
# ...
# $d variable is still indexed by key, but not by integer index
$d['b']
# returns: 10
# request the first item in the dictionary by numerical index
$d[0]
# returns: nothing/null, this is undesired behaviour. AARGH!
当然,我相信反序列化的有序字典应该像有序字典在它被持久化到磁盘之前一样,特别是能够通过数字索引和键检索哈希表项。
由于目前在 Powershell 中不是这种情况,是否有一种快速的方法可以将反序列化对象转换为对象的基本版本,而无需对整个反序列化对象执行 foreach?
【问题讨论】:
-
这似乎在 PowerShell v5 中也被破坏了。您可以导出
System.Collections.Specialized.OrderedDictionary,但导入 XML 会生成System.Collections.Hashtable。我想知道this 是否完全相关。 -
有趣。显然,对象序列化和反序列化,只是对象的反序列化版本缺少基础对象的某些功能。我只是希望通过巧妙的小转折来解决讨厌的问题的 Powershell 精神能够体现出来。我有代码循环遍历反序列化的对象并重新水合原始对象的全功能版本,但速度很慢。 “我讨厌等待!”
-
您可以尝试在PowerShell GitHub 上提交问题。还有来自“脚本专家”团队之一的 [this
ConvertTo-OrderedDictionary.ps1script}(gallery.technet.microsoft.com/scriptcenter/…)。不过,逻辑非常简单。 -
虽然 dotnet
PSSerializer序列化程序似乎保留了顺序,但反序列化程序(包括DeserializeAsList(String))也不会保留顺序。
标签: .net powershell