[英]PowerShell array null issue at class instantiation
我在課堂上初始化數組時遇到問題。 在該類的構造函數中,我設置了層次結構深度,以后將用於初始化該大小的數組。 如果我只使用[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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.