Powershell类实现get set属性 [英] Powershell class implement get set property
问题描述
如何使用Powershell类实现get / set属性。
请在下面的示例中查看:
How can i implement a get/set property with Powershell class. Please have a look on my example below:
Class TestObject
{
[DateTime]$StartTimestamp = (Get-Date)
[DateTime]$EndTimestamp = (Get-Date).AddHours(2)
[TimeSpan] $TotalDuration {
get {
return ($this.EndTimestamp - $this.StartTimestamp)
}
}
hidden [string] $_name = 'Andreas'
[string] $Name {
get {
return $this._name
}
set {
$this._name = $value
}
}
}
New-Object TestObject
推荐答案
您可以使用 Add-Member ScriptProperty
来实现某种吸气剂和吸气剂:
You can use Add-Member ScriptProperty
to achieve a kind of getter and setter:
class c {
hidden $_p = $($this | Add-Member ScriptProperty 'p' `
{
# get
"getter $($this._p)"
}`
{
# set
param ( $arg )
$this._p = "setter $arg"
}
)
}
更新它会调用 $ _ p
的初始化程序,这会添加脚本属性 p
:
Newing it up invokes the initializer for $_p
which adds scriptproperty p
:
PS C:\> $c = [c]::new()
并使用属性 p
产生以下内容:
And using property p
yields the following:
PS C:\>$c.p = 'arg value'
PS C:\>$c.p
getter setter arg value
此该技术存在一些陷阱,主要与 Add-Member
行的详细程度和错误程度有关。为了避免这些陷阱,我实现了 Accessor
,您可以在其中找到此处。
This technique has some pitfalls which are mostly related to how verbose and error-prone the Add-Member
line is. To avoid those pitfalls, I implemented Accessor
which you can find here.
使用 Accessor
代替 Add-Member
进行了大量的错误检查,并将原始类的实现简化为:
Using Accessor
instead of Add-Member
does an amount of error-checking and simplifies the original class implementation to this:
class c {
hidden $_p = $(Accessor $this {
get {
"getter $($this._p)"
}
set {
param ( $arg )
$this._p = "setter $arg"
}
})
}
这篇关于Powershell类实现get set属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!