PowerShell 5.0 Class Method Returns “Not all code

2019-07-29 16:35发布

问题:

As an experiment with PowerShell 5.0 classes I tried to translate JavaScript code for the Stable Marriage problem at Rosetta Code. It seemed very straight forward, but The second method (Rank) returns the error: Not all code path returns value within method.

class Person
{
    # --------------------------------------------------------------- Properties
    hidden [int]$CandidateIndex  = 0
    [string]$Name
    [person]$Fiance = $null
    [person[]]$Candidates = @()

    # ------------------------------------------------------------- Constructors
    Person ([string]$Name)
    {
        $this.Name = $Name       
    }

    # ------------------------------------------------------------------ Methods
    static [void] AddCandidates ([person[]]$Candidates)
    {
        [Person]::Candidates = $Candidates
    }

    [int] Rank ([person]$Person)
    {
        for ($i = 0; $i -lt $this.Candidates.Count; $i++)
        { 
            if ($this.Candidates[$i] -eq $Person)
            {
                return $i
            }

            return $this.Candidates.Count + 1
        }
    }

    [bool] Prefers ([person]$Person)
    {
        return $this.Rank($Person) -lt $this.Rank($this.Fiance)
    }

    [person] NextCandidate ()
    {
        if ($this.CandidateIndex -ge $this.Candidates.Count)
        {
            return $null
        }

        return $this.Candidates[$this.CandidateIndex++]
    }

    [int] EngageTo ([person]$Person)
    {
        if ($Person.Fiance)
        {
            $Person.Fiance.Fiance = $null
        }

        return $this.Fiance = $Person
    }

    [void] SwapWith ([person]$Person)
    {
        Write-Host ("{0} and {1} swap partners" -f $this.Name, $Person.Name)
        $thisFiance = $this.Fiance
        $personFiance = $Person.Fiance
        $this.EngageTo($personFiance)
        $Person.EngageTo($thisFiance)
    }
}

回答1:

The error is because if $this.Candidates.Count is 0, no return will execute.

Should the second return be outside of your for loop?

The current way, if it does not match the first candidate, it will return $this.Candidates.Count + 1.

[int] Rank ([person]$Person)
{
    for ($i = 0; $i -lt $this.Candidates.Count; $i++)
    { 
        if ($this.Candidates[$i] -eq $Person)
        {
            return $i
        }
    }
    return $this.Candidates.Count + 1
}