我的目标是创建一个自定义数据对象,它有两个离散变量(fooName
和fooUrl
)和一个列表fooChildren
,每个列表项都有两个离散变量变量childAge
和childName
。
目前,我有这个:
$fooCollection = [PSCustomObject] @{fooName=""; fooUrl=""; fooChildrenList=@()}
$fooCollection.fooName = "foo-a-rama"
$fooCollection.fooUrl = "https://1.2.3.4"
$fooChild = New-Object -TypeName PSobject
$fooChild | Add-Member -Name childAge -MemberType NoteProperty -Value 6
$fooChild | Add-Member -Name childName -MemberType NoteProperty -Value "Betsy"
$fooCollection.fooChildrenList += $fooChild
$fooChild = New-Object -TypeName PSobject
$fooChild | Add-Member -Name childAge -MemberType NoteProperty -Value 10
$fooChild | Add-Member -Name childName -MemberType NoteProperty -Value "Rolf"
$fooCollection.fooChildrenList += $fooChild
cls
$fooCollection.fooName
$fooCollection.fooUrl
foreach ($fooChild in $fooCollection.fooChildrenList)
{
(" " + $fooChild.childName + " " + $fooChild.childAge)
}
这会产生以下内容。到现在为止还挺好
foo-a-rama
https://1.2.3.4
Betsy 6
Rolf 10
问题:我不喜欢使用+=
,因为据我了解,每次执行都会+=
导致创建副本(无论处于何种状态) 。$fooCollection.fooChildrenList
+=
因此,我不想实现as ,而是实现fooChildrenList
as ,以便可以根据需要添加每一行。我已经尝试了各种在代码中执行此操作的方法,但最终无人居住。例如:@()
fooChildrenList
New-Object System.Collections.ArrayList
fooChildrenList
$fooCollection = [PSCustomObject] @{fooName=""; fooUrl=""; fooChildrenList = New-Object System.Collections.ArrayList}
$fooCollection.fooName = "foo-a-rama"
$fooCollection.fooUrl = "https://1.2.3.4"
$fooChild.childName = "Betsy"
$fooChild.childAge = 6
$fooCollection.fooChildrenList.Add((New-Object PSObject -Property $fooChild))
$fooChild.childName = "Rolf"
$fooChild.childAge = 10
$fooCollection.fooChildrenList.Add((New-Object PSObject -Property $fooChild))
$fooCollection | get-member
节目
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
fooChildrenList NoteProperty System.Collections.ArrayList fooChildrenList=
fooName NoteProperty string fooName=foo-a-rama
fooUrl NoteProperty string fooUrl=https://1.2.3.4
$fooCollection
节目
fooName : foo-a-rama
fooUrl : https://1.2.3.4
fooChildrenList : {}
如何将 System.Collections.ArrayList 添加到 PowerShell 自定义对象?