Loï*_*HEL 2 powershell events powershell-3.0 psobject
假设我有一个像这样的 psobject :
$o=New-Object PSObject -Property @{"value"=0}
Add-Member -MemberType ScriptMethod -Name "Sqrt" -Value {
echo "the square root of $($this.value) is $([Math]::Round([Math]::Sqrt($this.value),2))"
} -inputObject $o
Run Code Online (Sandbox Code Playgroud)
是否可以附加一个事件,以便在值属性更改时执行 Sqrt() 方法?IE :
PS>$o.value=9
Run Code Online (Sandbox Code Playgroud)
将产生
the square root of 9 is 3
Run Code Online (Sandbox Code Playgroud)
根据@Richard 的回答,这是有效的配方:
$o=New-Object PSObject -property @{"_val"=1}
Add-Member -MemberType ScriptMethod -Name "Sqrt" -Value {
write-host "the square root of $($this._val) is $([Math]::Round([Math]::Sqrt($this._val),2))"
} -inputObject $o
Add-Member -MemberType ScriptProperty -Name 'val' -Value{ $this._val } -SecondValue { $this._val=$args[0];$this.Sqrt() } -inputObject $o
Run Code Online (Sandbox Code Playgroud)
这包括定义单独的 getvalue和set 方法,而不是直接修改字段,而不是使其NoteProperty成为 a 。ScriptProperty
$theObject | Add-Member -MemberType ScriptProperty -Name 'Value'
-Value{ $this._value }
-SecondValue { $this._value = $args[0]; $this.Sqrt }
Run Code Online (Sandbox Code Playgroud)
(Value定义了 get 方法、SecondValueset 方法。)
请注意,由于 PowerShell 不提供任何封装数据的功能,因此调用者仍然可以访问底层字段。用 C#(或其他 .NET 语言)编写自定义类型并使用Add-Type可以避免这种情况,但不太值得,除非确实有不遵守规则的调用者。
第二期
在 ScriptProperty 中,没有输出管道(任何输出都会被丢弃),因此echo(作为 的别名Write-Output)不会做任何有用的事情。用Write-Host作品代替它。一般来说,属性获取或设置(包括输出)中的副作用是不好的做法(使用它们时预计开销较低)。
| 归档时间: |
|
| 查看次数: |
968 次 |
| 最近记录: |