Powershell覆盖父类构造函数

时间:2017-06-16 23:48:12

标签: powershell oop inheritance constructor

完全覆盖父构造函数的语法是什么?

在下面的代码中,我创建了一个Animals类和一个继承自Animals类的Dogs类。狗类有它的'拥有构造函数,但它不是替换Animals构造函数,而是在实例化类时运行Animals构造函数和Dogs构造函数。

class Animals {
    [System.Collections.ArrayList]$animalList = @()
    Animals() {
        $this.animalList.add("moose")
        $this.animalList.add("elephant")
        $this.animalList.add("buffalo")
    }
    showAnimals() {
        foreach($animal in $this.animalList) {
            Write-Host $animal
        }
    }
}
class Dogs : Animals {
    Dogs() {
        $this.animalList.add("Doberman")
        $this.animalList.add("Golden Retriever")
    }
}

$someAnimals = New-Object Animals
$someDogs = New-Object Dogs
Write-Host "The animals list:"
$someAnimals.showAnimals()
Write-Host ""
Write-Host "The dogs list:"
$someDogs.showAnimals()

这会产生以下结果:

The animals list:
moose
elephant
buffalo

The dogs list:
moose
elephant
buffalo
Doberman
Golden Retriever

1 个答案:

答案 0 :(得分:3)

您可以在构造函数中使用方法,并将此方法重写为派生类。像这样:

class Animals {
    [System.Collections.ArrayList]$animalList = @()
    Animals() 
    {
        $this.addAnimals()
    }

    [void] addAnimals() 
    {
        $this.animalList.add("moose")
        $this.animalList.add("elephant")
        $this.animalList.add("buffalo")
    }

    [void] showAnimals() {
        foreach($animal in $this.animalList) {
            Write-Host $animal
        }
    }
}

class Dogs : Animals {

    [void] addAnimals() 
    {
        $this.animalList.add("Doberman")
        $this.animalList.add("Golden Retriever")
    }
}


Write-Host ""
Write-Host ""

$someAnimals = New-Object Animals
Write-Host "The animals list:"
$someAnimals.showAnimals()
Write-Host ""

$someDogs = New-Object Dogs
Write-Host "The dogs list:"
$someDogs.showAnimals()