gpt4 book ai didi

class - 在实例化时为 PowerShell 类设置属性

转载 作者:行者123 更新时间:2023-12-02 22:34:11 26 4
gpt4 key购买 nike

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

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

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

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

最佳答案

不幸的是,您不能使用 : this() 调用同一类中的其他构造函数(尽管您可以 使用调用基类构造函数: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] 此设计限制 的原因,如 provided by a member of the PowerShell team是:

We did not add : this() syntax because there is a reasonable alternative that is also somewhat more intuitive syntax wise

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

关于class - 在实例化时为 PowerShell 类设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com