我在课堂上初始化数组时遇到问题。在该类的构造函数中,我设置了层次结构深度,以后将用于初始化该大小的数组。如果我只使用[int] $ Depth = 8,那么一切正常,但是,如果我尝试通过构造函数传递$ Depth,则它不起作用(错误:无法索引为空数组)。我在做什么错了?
部分代码:
class Hierarchy {
[int]$Depth = 8 // If I add a number here it works
[string]$Name
[string]$HideMembers
#Constructor
Hierarchy ([string] $Name, [string] $HideMembers, [int] $Depth)
{
$this.Name = $Name
$this.HideMembers = $HideMembers
$this.Depth = $Depth // it seems this is executed after the creation of the $levels array
}
[Level[]]$Levels = [Level[]]::new($this.Depth)
答案 0 :(得分:1)
我会这样:
class Hierarchy {
[int]$Depth
[string]$Name
[string]$HideMembers
[Level[]]$Levels
#Constructor
Hierarchy ([string] $Name, [string] $HideMembers, [int] $Depth)
{
$this.Name = $Name
$this.HideMembers = $HideMembers
$this.Depth = $Depth
$this.Levels = [Level[]]::new($this.Depth)
}
}
然后使用:
$hierarchy = New-Object Hierarchy "name", "hideMembers", 5