简体   繁体   中英

PowerShell array null issue at class instantiation

I am having an issue with initializing an array in my class. In the constructor of the class I set a hierarchy depth to be later used for initializing an array of that size. If I just use [int]$Depth = 8 everything works fine, however if I try to pass the $Depth via the constructor it is not working (Error: Cannot index into a null array). What am I doing wrong?

Part of the code:

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)

I would do it like this:

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)
    }

}

And then create with:

$hierarchy = New-Object Hierarchy "name", "hideMembers", 5

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM