下面的例子应该让你现在就开始吧!
您只需将[] 放在类型后面即可定义一个对象数组,因此Volume[]
sn-p 的底部还有 2 个示例,展示了如何访问卷数据。
Class Volume {
[String]$ID
[String]$Name
}
Class Storage {
[String]$Name
[String]$IP
[Volume[]]$Volumes
}
# Create a volume object
$volume1 = New-Object Volume
$volume1.ID = '1'
$volume1.Name = 'Data'
# Create another volume object
$volume2 = New-Object Volume
$volume2.ID = '2'
$volume2.Name = 'Log'
# Create a storage object
$storage = New-Object Storage
$storage.Name = 'SomeStorage'
$storage.IP = '0.0.0.0'
# Add the volume objects
$storage.Volumes += $volume1
$storage.Volumes += $volume2
# access a volume by name or index
$storage.Volumes | Where-Object {$_.Name -eq 'Data'}
$storage.Volumes[0]
zett42 和 santiago squarzon 的教育 N.B
当你一个一个地添加许多元素时,数组是低效的。您可能想看看 ArrayList / List 类型。
您可以在 Storage 类中改用 [List[Volume]]$Volumes = [List[Volume]]::new()。确保将using namespace System.Collections.Generic 放在脚本的顶部。然后当你添加卷时做$storage.Volumes.Add($volume1)
我为此做了一些性能测试,我向对象添加了 10_000 个卷。数组耗时 9.3 秒,列表耗时 0.93 秒,性能提升 10 倍。
数组 - 二次 - O(N²)
+= 重新创建整个数组,它将旧内容与新元素一起复制到新数组中。
ArrayList - 常量 - O(1)
ArrayList 对于任意添加/删除索引的时间复杂度为 O(n),但对于列表末尾的操作,时间复杂度为 O(1)。
using namespace System.Collections.Generic
Class Volume {
[String]$ID
[String]$Name
}
Class Storage {
[String]$Name
[String]$IP
[List[Volume]]$Volumes = [List[Volume]]::new()
}
# Create volume objects
$volume1 = New-Object Volume
$volume1.ID = '1'
$volume1.Name = 'Data'
# Create another volume object
$volume2 = New-Object Volume
$volume2.ID = '2'
$volume2.Name = 'Log'
# Create a storage object
$storage = New-Object Storage
$storage.Name = 'SomeStorage'
$storage.IP = '0.0.0.0'
# Add the volume objects
$storage.Volumes.Add($volume1)
$storage.Volumes.Add($volume2)
# access a volume by name or index
$storage.Volumes | Where-Object {$_.Name -eq 'Data'}
$storage.Volumes[0]