PowerShell Constructor Chain - Calling Other Constructors in the Same Class

I tested and came across the following:

You can overload methods in PoShv5 as you wish. If you call a method with no parameters, it can internally call a method with parameters so that your code is not redundant. I expected this to be true for designers as well.

In this example, the last constructor works as expected. Other constructors return objects with no given values.

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

Is there any way to fix this? Did I miss something?

+4
source share
2 answers

. , :

:

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 (, ); , , .

  • , #.

+6

TL; DR: !


, ( , ), , , #:

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# - :-)

.

+5

Source: https://habr.com/ru/post/1678704/


All Articles