“错误:并非所有代码路径都会返回值。”

2023-11-29

我的代码在编译时抛出名义异常。我不明白为什么会发生这种情况,因为经过广泛搜索后,发生错误的原因似乎只有在没有退出返回语句的情况下才存在,但我认为我的代码是完全包容的。

bool CheckExisting()
{
    Account loginAcc = new Account();

    string path = Application.StartupPath.ToString() + "\\Customers";
    int fCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length;
    for(int i = 0;i<fCount;i++)
    {
        String[] filePaths = Directory.GetFiles(Application.StartupPath + "\\Customers\\");
        XmlDocument xmlFile =new XmlDocument();
        xmlFile.Load(filePaths[i]);

        foreach(XmlNode node in xmlFile.SelectNodes("//Account"))
        {
            string firstName = node.SelectSingleNode("FirstName").InnerText;
            string lastName = node.SelectSingleNode("LastName").InnerText;
            string address1 = node.SelectSingleNode("Address1").InnerText;
            string address2 = node.SelectSingleNode("Address2").InnerText;
            string postCode = node.SelectSingleNode("Postcode").InnerText;
             string telePhone = node.SelectSingleNode("Telephone").InnerText;
            string mobile = node.SelectSingleNode("Mobile").InnerText;

            Account newAcc = new Account();

            newAcc.firstName = firstName;
            newAcc.lastName = lastName;
            newAcc.address1 = address1;
            newAcc.address2 = address2;
            newAcc.postCode = postCode;
            newAcc.telephone = telePhone;
            newAcc.mobile = mobile;

            loginAcc = newAcc;
        }

        if(txtFirstName.Text == loginAcc.firstName && txtLastName.Text == loginAcc.lastName)
        {
            return true;
        }
        else
        {
            return false;
        }
        return false;
    }
}

您的代码实际上是:

bool CheckExisting()
{
    // Some setup code

    for (int i = 0; i < fCount; i++)
    {
        // Code which isn't terribly relevant
        return ...;
    }
}

现在,C# 5 语言规范第 8.8.3 节讨论了 a 结尾的可达性for陈述:

a 的终点for如果以下至少一项为真,则语句可达:

  • The for语句包含可达的break退出的语句for陈述。
  • The for声明是可达的并且对于条件存在并且不具有恒定值true.

在这种情况下后者是正确的,所以结束for语句是可达的...这就是该方法的结尾。具有非 void 返回类型的方法的末尾永远无法到达。

请注意,即使human可以检测到您永远无法到达 for 语句的末尾。例如:

bool Broken()
{
    for (int i = 0; i < 5; i++)
    {
        return true;
    }
    // This is still reachable!
}

We知道循环总是至少执行一次,但语言规则不会执行 - 因此语句的末尾是可以到达的,并且您会收到编译时错误。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“错误:并非所有代码路径都会返回值。” 的相关文章

随机推荐