Powershell 克隆有序哈希表

Powershell Clone Ordered Hashtable

来自 的跟进。

问题

无法克隆有序哈希表。

问题

有没有 "easy" 方法来做到这一点?对于这样的 "simple" 任务,我确实发现了一些看起来过于复杂的示例。

MWE

$a = [ordered]@{}
$b = $a.Clone()

输出

Method invocation failed because [System.Collections.Specialized.OrderedDictionary] does not contain a method named 'Clone'.

OrderedDictionary do not contain Clone 方法(另见 ICloneable 接口)。您必须手动执行此操作:

$ordered = [ordered]@{a=1;b=2;c=3;d=4}
$ordered2 = [ordered]@{}
foreach ($pair in $ordered.GetEnumerator()) { $ordered2[$pair.Key] = $pair.Value }

虽然 Paweł Dyl 给出的答案确实克隆了有序哈希,但它不是 Deep-Clone

为此,您需要这样做:

# create a deep-clone of an object
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $ordered)
$ms.Position = 0
$clone = $bf.Deserialize($ms)
$ms.Close()

如果您愿意失去它的有序方面,一个快速的解决方案可能是转换为普通哈希表并使用其 Clone() 方法。

$b=([hashtable]$a).Clone()