PowerShell - クラス
バージョン5からクラスが使用可能になったようです。
class Person {
[string] $name
[int] $age
# コンストラクタ
Person() {
$this.name = "No Name"
$this.age = 0
}
Person([string]$name, [int]$age) {
$this.name = $name
$this.age = $age
}
# メソッド
[string]getName(){
return $this.name
}
[int]getAge(){
return $this.age
}
[void]talk([string]$str){
Write-Host "${str}, I'm $($this.name), $($this.age) years old."
}
}
$someone = New-Object Person
Write-Host $someone.getName() # No Name
Write-Host $someone.getAge() # 0
$taro = New-Object Person("Taro",20)
$taro.talk("Hello") # Hello, I'm Taro, 20 years old.
継承
いまのところ、親クラスのコントラクタやメソッドを呼ぶ方法が不明です。
class Employee : Person {
[int]$id
Employee(){
$this.id = 0
}
Employee([string]$name, [int]$age, [int]$id) {
$this.name = $name
$this.age = $age
$this.id = $id
}
# メソッドの上書き
[void]talk([string]$str){
Write-Host "${str}, I'm $($this.name), $($this.age) years old."
Write-Host "My ID is $($this.id)."
}
}
$jiro = New-Object Employee("Jiro",20, 1234)
$jiro.talk("Good Morning")
# Good Morning, I'm Jiro, 20 years old.
# My ID is 1234.