PowerShell 5.0 Class Method Returns “Not all code path returns value within method”

只谈情不闲聊 提交于 2019-12-11 08:37:01

问题


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
}


来源:https://stackoverflow.com/questions/41455833/powershell-5-0-class-method-returns-not-all-code-path-returns-value-within-meth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!