我正在處理一個帶有小型 WPF GUI 的 PowerShell 腳本。我的代碼組織在一個類中,從中創建一個單例。我已經讀到事件處理程式腳本塊中的 $this 指向事件發送者而不是我的包含類實體。如何從事件處理程式訪問我的類實體?
前任。
class MyClass {
$form #Reference to the WPF form
[void] StartAction([object] $sender, [System.Windows.RoutedEventArgs] $e) {
...
}
[void] SetupEventHandlers() {
$this.form.FindName("BtnStartAction").add_Click({
param($sender, $e)
# !!!! Does not work, $this is not my class instance but the event sender !!!!
$this.StartAction($sender, $e)
})
}
[void] Run() {
$this.InitWpf() #Initializes the form from a XAML file.
$this.SetupEventHandlers()
...
}
}
$instance = [MyClass]::new()
$instance.Run()
uj5u.com熱心網友回復:
實際上,充當.NET 事件處理程式的腳本塊中的自動
$this變數指的是事件發送者。如果事件處理程式腳本塊是從PowerShell 自定義
class的方法內部設定的,則事件發送者的定義會$this隱藏類方法中的通常定義(指手頭的類實體)。
有兩種解決方法,都依賴于 PowerShell 的動態范圍,它允許后代作用域查看祖先作用域中的變數。
- 使用以參考父范圍的值(事件處理程式腳本塊的運行子范圍呼叫者的)。
Get-Variable-Scope 1$this
[void] SetupEventHandlers() {
$this.form.FindName("BtnStartAction").add_Click({
param($sender, $e)
# Get the value of $this from the parent scope.
(Get-Variable -ValueOnly -Scope 1 this).StartAction($sender, $e)
})
}
- 更直接地利用動態范圍,您可以采用Abdul Niyas PM的建議,即在呼叫方的范圍中定義一個輔助變數,該變數以不同的名稱參考自定義類實體,您可以在其中參考 - 可能是多個 -從相同的方法設定的事件處理程式腳本塊:
[void] SetupEventHandlers() {
# Set up a helper variable that points to $this
# under a different name.
$thisClassInstance = $this
$this.form.FindName("BtnStartAction").add_Click({
param($sender, $e)
# Reference the helper variable.
$thisClassInstance.StartAction($sender, $e)
})
}
另請注意,從 PowerShell 7.2 開始,您不能直接使用自定義類方法作為事件處理程式-此答案顯示了解決方法,這也需要解決$this陰影問題。
uj5u.com熱心網友回復:
試試這個樣本
class MyClass {
$form #Reference to the WPF form
[void] StartAction([System.Windows.RoutedEventArgs] $e) {
#$this ...
}
[void] SetupEventHandlers() {
$this.form.FindName("BtnStartAction").add_Click({
param($sender, $e)
([MyClass]$sender).StartAction($e)
})
}
[void] Run() {
$this.InitWpf()
$this.SetupEventHandlers()
}
}
$instance = [MyClass]::new()
$instance.Run()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/363476.html
標籤:电源外壳
