如何創建具有靜態變數的 powershell 類?
class ex1 {
static [int]$count = 0
ex1() {
[ex1]::count = [ex1]::count 1
write-host [ex1]::count
}
}
$ex1 = [ex1]::new()
$ex2 = [ex1]::new()
$ex3 = [ex1]::new()
exit 1
我試過這個,但它所做的一切都列印:
[ex1]::new()
[ex1]::new()
[ex1]::new()
而不是增加計數來計算靜態整數中創建的物件數。
uj5u.com熱心網友回復:
除了建構式之外ex1() {..},您還需要添加一個實際回傳靜態屬性值的方法Count:
class ex1 {
[int]static $count = 0
ex1() {
# constructor increments the static Count property
[ex1]::count
}
[int]GetCount() {
# simply return the current value of Count
return [ex1]::count
}
}
$ex1 = [ex1]::new().GetCount()
$ex2 = [ex1]::new().GetCount()
$ex3 = [ex1]::new().GetCount()
$ex1, $ex2, $ex3 # --> resp. 1, 2, 3
uj5u.com熱心網友回復:
靜態屬性有效,但令人驚訝的是,PowerShell 決議器在遇到函式引數時并沒有離開引數模式[ex1]::count,而是將其決議為文字字串。
內附[ex1]::count迫使決議器離開引數模式和決議運算式括號解決了這個問題。
class ex1 {
static [int]$count = 0
ex1() {
[ex1]::count = [ex1]::count 1
write-host ([ex1]::count)
}
}
$ex1 = [ex1]::new()
$ex2 = [ex1]::new()
$ex3 = [ex1]::new()
[ex1]::count # Works without parentheses, as we are not in argument mode.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316405.html
標籤:电源外壳
