見出し画像

PowerShellでクラスをつかう

PowerShellでクラスをつかうときのメモです


class Animal {
 [string]$name
 [int]$age
 [string]$color

 Animal() {
 }

 init ([string]$name="", [int]$age=0, [string]$color="") {
  $this.name = $name
  $this.age = $age
  $this.color = $color
 }

 [string]ToString() {
  return "name:$($this.name) age:$($this.age) color:$($this.color)"
 }
}

class Person : Animal {
 [string]ToString() {
  return "この人の名前は $($this.name) です 年齢は $($this.age) 才"
 }

}

$cat = [Animal]::new()
$cat.init("tama", 3, "brown tiger")
Write-Output $cat.ToString()

$people = [Animal]::new()
$people.init("Donald John Trump", 77, "purple")
Write-Output $people.ToString()


class Animal{}のところでAnimalクラスという定義しています。
class Person:Animal{}はAnimalクラスを元にPersonクラスを定義。メソッドToString()を上書きしています。

クラスの使い方は
$cat=[Animal]::new()
で初期化
$cat.init()や$cat.toString()でメソッドを呼び出しています。

PowerShellでも他の言語と同じようなクラスの機能があります。


toString()の動作が$cstと$peopleで違う


#PowerShell #プログラミング学習 #クラス #クラス継承 #オーバーライド #Windows #it

この記事が気に入ったらサポートをしてみませんか?