4
public partial class KalenderLeeftijd : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void calBirthDate_SelectionChanged(object sender, EventArgs e)
{

}
private string GetAnswer()
{
    DateTime birthday = calBirthDate.SelectedDate;
    TimeSpan difference = DateTime.Now.Date - birthday;
    int leapYears = CountLeapYears(birthday);

    int days = (int)difference.TotalDays - leapYears;
    int hours = (int)difference.TotalHours - leapYears * 24;

    int years = days / 365;

    String answer = String.Format("Age: {0} years", years);
    answer += Environment.NewLine;
    answer += String.Format("Days: {0}*365+{1} = {2}", years, days - years * 365, days);
    answer += Environment.NewLine;
    answer += String.Format("Days Hours: {0}*24 = {1}", hours / 24, hours);
    return answer;
}

private int CountLeapYears(DateTime startDate)
{
    int count = 0;
    for (int year = startDate.Year; year <= DateTime.Now.Year; year++)
    {
        if (DateTime.IsLeapYear(year))
        {
            DateTime february29 = new DateTime(year, 2, 29);
            if (february29 >= startDate && february29 <= DateTime.Now.Date)
            {
                count++;
            }
        }
    }
    return count;
    String answer = GetAnswer();
    Response.Write(lblAntwoord); 
}
}

为什么我会收到错误消息:“检测到无法访问的代码”?- 错误显示在以下行 -String answer = GetAnswer();

4

4 回答 4

28

这只是因为您的代码位于 return 语句之后。

return 语句终止它出现的方法的执行,并将控制权返回给调用方法。它还可以返回一个可选值。如果方法是 void 类型,return 语句可以省略。

如果 return 语句在 try 块内,则 finally 块(如果存在)将在控制返回调用方法之前执行。

http://msdn.microsoft.com/en-us/library/1h3swy84%28v=vs.100%29.aspx

解决方案(明显):

将无法访问的代码移到 return 语句之前。

于 2012-09-21T08:42:53.750 回答
7

无法访问的代码是编译器警告,而不是错误。你有三个选择:

它是不可达的,因为方法流在return语句处退出,因此永远不会执行下面的代码。编译器可以确定这一点,因此可以报告它。就像我说的那样,这些实际上是编译器警告,除非您已将项目配置为将警告视为错误,否则它们不会停止成功的构建。

于 2012-09-21T08:43:47.133 回答
2

该声明:

return count;

退出该功能。所以,

answer = GetAnswer(); 
Response.Write(lblAntwoord);  

无法连接。

于 2012-09-21T08:43:38.693 回答
0

return语句终止函数的执行并将控制权返回给调用函数。在调用函数的紧接着调用点处继续执行

如果函数定义中没有出现return语句,则在执行被调用函数的最后一条语句后,控制自动返回调用函数

在您的代码中:

private int CountLeapYears(DateTime startDate)
{
    int count = 0;
    for (int year = startDate.Year; year <= DateTime.Now.Year; year++)
    {
        if (DateTime.IsLeapYear(year))
        {
            DateTime february29 = new DateTime(year, 2, 29);
            if (february29 >= startDate && february29 <= DateTime.Now.Date)
            {
                count++;
            }
        }
    }
    return count;//The Execution will be terminated here,the next lines will become unreachable 
    **String** answer = GetAnswer();
    Response.Write(lblAntwoord); 
}
}

MSDN 链接:

C:https ://msdn.microsoft.com/en-us/library/sta56yeb.aspx

c#:https ://msdn.microsoft.com/en-us/library/1h3swy84.aspx

于 2016-09-07T07:07:14.007 回答