我正在尝试使用$backUp
方法将字典克隆到名为.clone()
的变量中,但它失败并出现错误:
方法调用失败,因为 [System.Collections.Generic.Dictionary`2 [[System.String,mscorlib, 版本= 4.0.0.0,文化=中立, PublicKeyToken = b77a5c561934e089],[System.String,mscorlib, Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]] 不包含名为“克隆”的方法。在行:10 char:1 + $ backUp = $ originalKeyValuePairs.Clone() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidOperation:(:) [],RuntimeException + FullyQualifiedErrorId:MethodNotFound
$originalKeyValuePairs = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$originalKeyValuePairs.add("key1", "value1")
$originalKeyValuePairs.add("key2", "value2")
$originalKeyValuePairs.add("key3", "value3")
$originalKeyValuePairs.add("key4", "value4")
Write-Output "This is the original dictionary" $originalKeyValuePairs
#Copy the "originalKeyValuePairs" into a variable
$backUp = $originalKeyValuePairs.Clone()
#update the 'key2' value to something else:
$originalKeyValuePairs["key2"] = "tempvalue"
#Now I'm done with updating the values. Now I want to restore my "$backUp" into the $originalKeyValuePairs
$originalKeyValuePairs = $backUp.clone()
Write-Output "Done with updating some of the value in original keyValuePairs and restore 'backUp' dictionary into 'originalKeyValuePairs'. Here is the unmodified dictionary" $originalKeyValuePairs
答案 0 :(得分:0)
您想要深度复制它而不是克隆它。查看this link
$originalKeyValuePairs = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$originalKeyValuePairs.add("key1", "value1")
$originalKeyValuePairs.add("key2", "value2")
$originalKeyValuePairs.add("key3", "value3")
$originalKeyValuePairs.add("key4", "value4")
Write-Output "This is the original dictionary" $originalKeyValuePairs
#Copy the "originalKeyValuePairs" into a variable
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $originalkeyvaluepairs)
$ms.Position = 0
$backup = $bf.Deserialize($ms)
$ms.Close()
#update the 'key2' value to something else:
$originalKeyValuePairs["key2"] = "tempvalue"
#Now I'm done with updating the values. Now I want to restore my "$backUp" into the $originalKeyValuePairs
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $backup)
$ms.Position = 0
$originalkeyvaluepairs = $bf.Deserialize($ms)
$ms.Close()
Write-Output "Done with updating some of the value in original keyValuePairs and restore 'backUp' dictionary into 'originalKeyValuePairs'. Here is the unmodified dictionary" $originalKeyValuePairs