Powershell 类实现 get set 属性 [英] Powershell class implement get set property

查看:24
本文介绍了Powershell 类实现 get set 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 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来实现一种getter和setter:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆