在实例化时设置 PowerShell 类的属性

2024-01-12

是否可以在实例化时定义 PowerShell 类的属性值而不使用构造函数?

假设有一个 cmdlet 将返回 Jon Snow 的当前状态(活着或死亡)。我希望该 cmdlet 将该状态分配给我的类中的属性。

我可以使用构造函数来做到这一点,但我希望无论使用哪个构造函数,甚至是否使用构造函数,都会发生这种情况。

function Get-JonsCurrentStatus {
    return "Alive"
}

Class JonSnow {

    [string]
    $Knowledge

    [string]
    $Status

    #Constructor 1
    JonSnow()
    {
        $this.Knowledge = "Nothing"
        $this.Status = Get-JonsCurrentStatus
    }

    #Constructor 2
    JonSnow([int]$Season)
    {
        if ($Season -ge 6) 
        {
            $this.Knowledge = "Still nothing"
            $this.Status = Get-JonsCurrentStatus #I don't want to have to put this in every constructor
        }
    }

}

$js = [JonSnow]::new()
$js

Unfortunately, you cannot call other constructors in the same class with : this() (though you can call a base class constructor with : base())[1]

你最好的选择是解决方法(隐藏)辅助方法:

function Get-JonsCurrentStatus {
    return "Alive"
}

Class JonSnow {

    [string]
    $Knowledge

    [string]
    $Status

    # Hidden method that each constructor must call
    # for initialization.
    hidden Init() {
      $this.Status = Get-JonsCurrentStatus
    }

    #Constructor 1
    JonSnow()
    {
        # Call shared initialization method.
        $this.Init()
        $this.Knowledge = "Nothing"
    }

    #Constructor 2
    JonSnow([int]$Season)
    {
        # Call shared initialization method.
        $this.Init()
        if ($Season -ge 6) 
        {
            $this.Knowledge = "Still nothing"
        }
    }

}

$js = [JonSnow]::new()
$js

[1] 这样做的原因设计限制, as 由 PowerShell 团队成员提供 https://github.com/PowerShell/PowerShell/issues/3820#issuecomment-302750422 is:

我们没有添加 : this() 语法,因为有一个合理的替代方案,而且语法也更直观

然后链接的评论推荐了该答案中使用的方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在实例化时设置 PowerShell 类的属性 的相关文章

随机推荐