Powershell:在新的 xml 变量或对象中保存 xml 更改,保持原始对象不变 [英] Powershell: saving xml changes in a new xml variable or object, keeping the original object unchanged

查看:53
本文介绍了Powershell:在新的 xml 变量或对象中保存 xml 更改,保持原始对象不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从 Invoke-restmethod 获得的 xml 变量.让我们称之为 $object1

I have a xml variable that I get from Invoke-restmethod. Lets call it $object1

我想创建一个与 $object1 相同的新变量或对象 $object2,但对值进行了一些更改

I want to make a new variable or object $object2 that is the same as $object1 but with a few changes to the values

这是我尝试过的:

$object2 = $object1

$object2.sweets.candy.Where({$_.lemondrop -gt 1}) | Foreach{$_.gumdrop = 20}

现在的问题是,当我仔细检查 $object1 时,那里的值也发生了变化......我不想要那个

Now the problem with that is when I double check $object1 the value is changed there too... I dont want that

我只希望更改保留在 $object2

我在这里做错了什么?

推荐答案

您需要克隆 $object1 以获得它的独立副本:

You need to clone $object1 in order to obtain an independent copy of it:

$object2 = $object1.Clone() # assumes that $object's type implements ICloneable

[System.Xml.XmlDocument] 是一个 引用类型(相对于 值类型[int]),意思是:

[System.Xml.XmlDocument] is a reference type (as opposed to a value type such as [int]), which means that:

$object2 = $object1

简单地使 $object2 引用(指向)与 $object1 完全相同的对象.

simply makes $object2 reference (point to) the very same object as $object1.

您可以通过以下方式验证:

You can verify this as follows:

[object]::ReferenceEquals($object1, $object2)

一般:

  • = 使用值类型 实例创建实际值的副本,即隐式克隆.

  • = with a value type instance creates a copy of the actual value, i.e., it implicitly clones.

= 带有引用类型 实例创建引用的副本 到实例,即它创建另一个对同一个对象的引用.

= with a reference type instance creates a copy of the reference to the instance, i.e., it creates another reference to the very same object.

同样适用于添加元素到(可变)集合;例如(假设已经用 $list = [System.Collections.Generic.List[object]] @() 创建了一个列表):

The same applies when you add elements to a (mutable) collection; e.g. (assume having created a list with $list = [System.Collections.Generic.List[object]] @()):

  • $var = 42;$list.Add($var)value-type ([int]) 实例的 copy 添加到列表中.
  • $var = [pscustomobject] @{ foo = 'bar' };$list.Add($var) 向列表添加一个 referencereference-type ([pscustomobject]) 实例.
  • $var = 42; $list.Add($var) adds a copy of the value-type ([int]) instance to the list.
  • $var = [pscustomobject] @{ foo = 'bar' }; $list.Add($var) adds a reference to the reference-type ([pscustomobject]) instance to the list.

确定给定类型是值类型还是引用类型,请使用该类型的布尔值.IsValueType 属性:

To determine if a given type is a value type or a reference type, use the type's Boolean .IsValueType property:

# Inspect a type directly.
PS> [System.Xml.XmlDocument].IsValueType
False    # -> a *reference* type

# Inspect a type via an instance thereof:
PS> $xml = [xml] '<xml/>'; $xml.GetType().IsValueType
False 

这篇关于Powershell:在新的 xml 变量或对象中保存 xml 更改,保持原始对象不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆