PowerShell 5.0类方法返回"并非所有代码路径都返回方法"

时间:2017-01-04 03:40:45

标签: powershell powershell-v5.0

作为PowerShell 5.0类的实验,我尝试在Rosetta Code中为稳定婚姻问题翻译JavaScript代码。它似乎很直接,但第二种方法(Rank)返回错误:并非所有代码路径都返回方法中的值。

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 个答案:

答案 0 :(得分:2)

错误是因为如果$this.Candidates.Count0,则不会执行任何返回。

第二次回归是否应该在你的for循环之外?

目前的方式,如果它与第一个候选人不匹配,它将返回$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
}