Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Class 在实例化时为PowerShell类设置属性_Class_Powershell - Fatal编程技术网

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

Class 在实例化时为PowerShell类设置属性,class,powershell,Class,Powershell,是否可以在实例化时定义PowerShell类的属性值而不使用构造函数 假设有一个cmdlet将返回Jon Snow的当前状态(活着或死去)。我希望该cmdlet将该状态分配给类中的属性 我可以使用构造函数来实现这一点,但我希望无论使用哪个构造函数,或者即使使用了一个构造函数,都能实现这一点 function Get-JonsCurrentStatus { return "Alive" } Class JonSnow { [string] $Knowledge

是否可以在实例化时定义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

不幸的是,您不能使用
: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] 设计限制导致此问题的原因如下:

我们没有添加:this()语法,因为有一个合理的替代方案,它在某种程度上也更直观


然后,链接注释推荐了此答案中使用的方法。

您可以通过以下方式初始化实例化时的类属性:

$jon = new-object JonSnow -Property @{"Status" = Get-JonsCurrentStatus; "Knowledge" = "Nothing"}

@ScubaManDan:事实证明,一个实例方法允许一个更简单的解决方案,我还添加了不支持这个的官方理由。顺便说一句,它可以缩短为
[jonsow]@{“Status”=Get JonsCurrentStatus;“Knowledge”=“Nothing”}
。很好的速记,我没有意识到这一点。我会让答案保持原样,因为我更喜欢它是冗长的,以便人们更好地理解正在发生的事情。