运行下面的代码时,我总是收到错误消息。我不明白我在做什么错
错误1:您不能在空值表达式上调用方法。在 行:25字符:9
错误2:无法索引为空数组。在第43行char:1
代码:
Class Step {
[int]$StepNumber = 0
[string]$Name = ''
[string]$ScriptFile = ''
[int]$status = 0 # 0 = 'InComplete', 1 = 'Complete', 2 = 'Failed', -1 = 'Skipped'
[string]$DependencyStepNumber = -1
Step([string]$Name, [int]$StepNumber, [string]$ScriptFile) {
$this.Name = $Name
$this.StepNumber = $StepNumber
$this.ScriptFile = $ScriptFile
}
}
Class Guide {
[int]$StepNumberCounter = 0
[string]$Name = ''
[Step[]]$Steps
[int]AddStep([string]$Name, [string]$ScriptFile) {
$newStepNumber = $this.GetNewStepNumber()
$newStep = [Step]::new($Name, $newStepNumber, $ScriptFile)
line-25>>> $this.Steps.Add($newStep)
return $newStepNumber
}
[int]GetStepName([int]$StepNumber) {
return $this.Steps[$StepNumber-1]
}
[int]GetNewStepNumber() {
return $this.StepNumberCounter += 1
}
}
$Guide = [Guide]::new()
$Guide.AddStep('Step One','ScriptOne.ps1')
$Guide.AddStep('Step Two','ScriptTwo.ps1')
line-43>>> Write-Host $Guide.Steps[0]
Write-Host $Guide.Steps[1]
答案 0 :(得分:1)
要向数组中添加元素,请使用+ =运算符。
$this.Steps += $newStep
为ArrayList保留添加:
$al = New-Object System.Collections.ArrayList
$al.Add('Example')
答案 1 :(得分:1)
数组列表具有更好的性能,请参见下面的修订代码
Class Step {
[int]$StepNumber = 0
[string]$Name = ''
[string]$ScriptFile = ''
[int]$status = 0 # 0 = 'InComplete', 1 = 'Complete', 2 = 'Failed', -1 = 'Skipped'
[string]$DependencyStepNumber = -1
Step([string]$Name, [int]$StepNumber, [string]$ScriptFile) {
$this.Name = $Name
$this.StepNumber = $StepNumber
$this.ScriptFile = $ScriptFile
}
}
Class Guide {
[int]$StepNumberCounter = 0
[string]$Name = ''
[System.Collections.ArrayList]$Steps = @()
[int]AddStep([string]$Name, [string]$ScriptFile) {
$newStepNumber = $this.GetNewStepNumber()
$newStep = [Step]::new($Name, $newStepNumber, $ScriptFile)
$this.Steps.Add($newStep)
return $newStepNumber
}
[int]GetStepName([int]$StepNumber) {
return $this.Steps[$StepNumber-1]
}
[int]GetNewStepNumber() {
return $this.StepNumberCounter += 1
}
}
$Guide = [Guide]::new()
$Guide.AddStep('Step One','ScriptOne.ps1')
$Guide.AddStep('Step Two','ScriptTwo.ps1')
Write-Output $Guide.Steps[0]
Write-Output $Guide.Steps[1]