powershell中的构造函数链 - 在同一类中调用其他构造函数



我正在进行一些测试并偶然发现以下内容:

您可以根据需要在POSHV5中超载方法。如果您无参数调用该方法,则可以内部用参数调用该方法,以使您的代码不冗余。我希望这对于构造函数也是如此。

在此示例中,最后一个构造函数正在按预期工作。其他构造函数仅返回没有设置值的对象。

Class car {
    [string]$make
    [string]$model
    [int]$Speed
    [int]$Year
    speedUp (){
        $this.speedUp(5)
    }
    speedUp ([int]$velocity){
        $this.speed += $velocity
    }
    # Constructor
    car () {
        [car]::new('mall', $Null, $null)
    }
    car ([string]$make, [string]$model) {
        [car]::new($make, $model, 2017)
    }
    car ([string]$make, [string]$model, [int]$Year) { 
        $this.make = $make
        $this.model = $model
        $this.Year = $year
    }
}
[car]::new() # returns "empty" car
[car]::new('Make', 'Nice model') # returns also an "empty" one
[car]::new( 'make', 'nice model', 2017) # returns a "filled" instance

有办法解决此问题吗?我错过了什么吗?

以补充Mathias R. Jessen的有益答案:

推荐的方法是使用隐藏的助手方法来补偿缺乏构造函数链接

Class car {
    [string]$Make
    [string]$Model
    [int]$Year
    speedUp (){
        $this.speedUp(5)
    }
    speedUp ([int]$velocity){
        $this.speed += $velocity
    }
    # Hidden, chained helper methods that the constructors must call.
    hidden Init([string]$make)                 { $this.Init($make, $null) }
    hidden Init([string]$make, [string]$model) { $this.Init($make, $model, 2017) }
    hidden Init([string]$make, [string]$model, [int] $year) {
        $this.make = $make
        $this.model = $model
        $this.Year = $year
    }
    # Constructors
    car () {
        $this.Init('Generic')
    }
    car ([string]$make) {
        $this.Init($make)
    }
    car ([string]$make, [string]$model) {
        $this.Init($make, $model)
    }
    car ([string]$make, [string]$model, [int]$year) { 
        $this.Init($make, $model, $year)
    }
}
[car]::new()                          # use defaults for all fields
[car]::new('Fiat')                    # use defaults for model and year
[car]::new( 'Nissan', 'Altima', 2015) # specify values for all fields

这产生:

Make    Model  Year
----    -----  ----
Generic        2017
Fiat           2017
Nissan  Altima 2015

注意:

  • hidden关键字更多是PowerShell本身观察到的 judent (例如,输出时省略此类成员(;成员以这种方式标记为技术仍然可以访问。

  • 虽然您无法直接调用 same 类的构造函数,但可以使用c# - base-class 构造函数来执行此操作。像语法。

tl; dr:no!


您要寻找的东西(超载的构造师连续呼叫(也被称为构造器链接,在C#中看起来大致像:

class Car
{
    string Make;
    string Model;
    int Year;
    Car() : this("mall", null)
    {
    }
    Car(string make, string model) : this(make, model, 2017) 
    {
    }
    Car(string make, string model, int Year) 
    { 
        this.Make = make;
        this.Model = model;
        this.Year = year;
    }
}

不幸的是,PowerShell似乎没有任何语法 - 您不能做:

Car() : $this("Porsche") {}
Car([string]$Make) {}

而没有让解析器扔给您,因为错过了您的构造函数的身体定义,我不希望很快就会看到它 - Powershell团队表达了明确的愿望,不要成为新的水的维护者C#-我完全可以很好地理解: - (

您只需要重新实现每个构造函数定义中的成员分配。

最新更新