[英]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).
如果我只使用[int] $ Depth = 8,那么一切正常,但是,如果我尝试通过构造函数传递$ Depth,则它不起作用(错误:无法索引为空数组)。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.