我正在做一些测试,偶然发现以下内容:
您可以根据需要在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本身遵守的约定(例如,在输出时省略此类成员)。但是,从技术上讲,仍可以使用这种方式标记的成员。 关于class - PowerShell中的构造函数链接-调用同一类中的其他构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44413206/