如何创建 PSObject 对象的新克隆实例 [英] How to create new clone instance of PSObject object

查看:28
本文介绍了如何创建 PSObject 对象的新克隆实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建我的自定义 PSObject 的新实例.我有一个创建为 PSObject 的 Button 对象,我想创建与 Button 具有相同成员的新对象 Button2,但我找不到如何克隆原始对象而不在原始对象中引用它的方法(如果我更改Button2 中的一个属性,它也在 Button 中更改).有没有一种方法可以通过某些 Clone() 方法与哈希表和数组类似?

I want to create new instance of my custom PSObject. I have a Button object created as PSObject and I want to create new object Button2 which has the same members as Button does, but I can't find a way how to clone the original object without making it referenced in original object (if I change a property in Button2 it changes in Button as well). Is there a way how to do it similarly as with hashtables and arrays via some Clone() method?

推荐答案

确实没有克隆方法!然而,只要有意愿......

Indeed there is no clone method! However where there is a will...

$o = New-Object PsObject -Property @{ prop1='a' ; prop2='b' }
$o2 = New-Object PsObject
$o.psobject.properties | % {
    $o2 | Add-Member -MemberType $_.MemberType -Name $_.Name -Value $_.Value
}
$o.prop1 = 'newvalue'

$o
$o2

输出:

prop2     prop1                                                                 
-----     -----                                                                 
b         newvalue                                                              
b         a      

这篇关于如何创建 PSObject 对象的新克隆实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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