小编res*_*987的帖子

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
Run Code Online (Sandbox Code Playgroud)

有没有办法来解决这个问题?我错过了什么?

powershell constructor overloading class constructor-chaining

10
推荐指数
2
解决办法
1715
查看次数