PowerShell克隆有序哈希表

5

来自这个帖子的后续。

问题

有序哈希表无法被克隆。

问题

有没有一种“简单”的方法来做到这一点?我确实找到了一些看起来对于这样一个“简单”任务来说过于复杂的示例。

MWE

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

输出

方法调用失败,因为[System.Collections.Specialized.OrderedDictionary]不包含名为'Clone'的方法。


3个回答

8

有序字典不包含Clone方法(也可以看看ICloneable接口)。您需要手动完成它:

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

4

尽管Paweł Dyl提供的答案复制了有序哈希,但它并不是深克隆

要实现深度克隆,您需要执行以下操作:

# 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()

1
如果您愿意放弃它的有序特性,一个快速的解决方案是将其转换为普通哈希表并使用其Clone()方法。
$b=([hashtable]$a).Clone()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接