PowerShell中的构造函数链接-调用同一类中的其他构造函数 [英] Constructor chaining in PowerShell - call other constructors in the same class

查看:33
本文介绍了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'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#的语法通过基类构造函数来执行此操作。

这篇关于PowerShell中的构造函数链接-调用同一类中的其他构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆