对于永远不会返回值的代码,获取“并非所有代码路径都会返回值”

问题描述 投票:0回答:1

虽然我写了所有可能的条件来返回值,但我编写的方法没有返回值。

我的理解是,每当编译器看到 return 关键字时,它就会停止,执行程序并返回 return 关键字旁边的值。即使它在循环中,它也会中断循环并返回值,但编译器会显示“not all code paths return a value”错误。对于其他可能的条件还有一个 else 条件以及错误是如何出现的。

那么,return 关键字实际上是如何工作的?

我很困惑。

using System;

public static class PhoneNumber
{
    public static (bool IsNewYork, bool IsFake, string LocalNumber) Analyze(
        string phoneNumber)
    {
        bool flag = true;
        string[] numSub = phoneNumber.Split("-");
        while(flag)
        {
            if(numSub[0] == "212")
            {
                if(numSub[1] == "555")
                {
                    return (true, true, numSub[2]);
                }
                else
                {
                    return (true, false, numSub[2]);
                }
            } // end of if condition
            else
            {
                if(numSub[1] == "555")
                {
                    return (false, true, numSub[2]);
                }
                else
                {
                    return (false, false, numSub[2]);
                }
            } // end of the else condition
        } // end of the loop
    }
}
c# loops compiler-errors return
1个回答
3
投票

并非所有代码路径都会返回值

编译器不够“聪明”,无法知道您将进入

while
循环。 因此,它将不进入
while
循环的代码路径视为没有
return
的可能代码路径。

编写的代码结构没有多大意义,因此可能应该对其进行重组以使编译器满意,并且更易于阅读和维护。 您也可以在

while
之后抛出异常来消除编译错误。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.