Arrays 类实例化时PowerShell数组null问题

Arrays 类实例化时PowerShell数组null问题,arrays,powershell,class,Arrays,Powershell,Class,我在初始化类中的数组时遇到问题。在类的构造函数中,我设置了一个层次结构深度,稍后用于初始化该大小的数组。如果我只使用[int]$Depth=8,一切正常,但是如果我试图通过构造函数传递$Depth,它就不起作用(错误:无法索引到空数组)。我做错了什么 守则的一部分: class Hierarchy { [int]$Depth = 8 // If I add a number here it works [string]$Name [string]$HideMembers #Construct

我在初始化类中的数组时遇到问题。在类的构造函数中,我设置了一个层次结构深度,稍后用于初始化该大小的数组。如果我只使用[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)

我会这样做:

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

谢谢你,阿罗辛!似乎我让我的生活变得更加艰难;-)