class - PowerShell中的构造函数链接-调用同一类中的其他构造函数

标签 class powershell constructor overloading constructor-chaining

我正在做一些测试,偶然发现以下内容:

您可以根据需要在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's helpful answer:

recommended approach使用隐藏的帮助器方法来补偿缺少构造函数链接的方法:

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本身遵守的约定(例如,在输出时省略此类成员)。但是,从技术上讲,仍可以使用这种方式标记的成员。
  • 虽然您不能直接调用同一类的构造函数,但可以使用类似于C#的语法使用基类构造函数来进行调用。
  • 关于class - PowerShell中的构造函数链接-调用同一类中的其他构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44413206/

    相关文章:

    powershell - TFS 2010 Powershell Get-TFSItemHistory返回最旧的版本,而不是最新的版本

    javascript - 访问构造函数创建的对象中的属性

    python - 如何只获取父类对象的属性

    c++ - 在派生构造函数中生成参数时,如何将参数传递给默认构造函数?

    powershell - 查找特定文件并删除它(如果存在)

    java - 通过构造函数传递数组

    c++ - 传递一个空的 vector 参数

    c++ - 请求模板类的成员

    c++ - 是否有任何理由不扩展 std::set 以添加下标运算符?

    html - 在电子邮件中嵌入图像并通过 Powershell 发送