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();
答案 0 :(得分:19)
这只是因为你的代码在return语句之后。
return语句终止执行的方法 出现并将控制权返回给调用方法。它也可以回归 可选值。如果方法是void类型,则返回语句 可以省略。
如果return语句在try块内,则finally控件(如果存在)将在控制返回调用方法之前执行。
http://msdn.microsoft.com/en-us/library/1h3swy84%28v=vs.100%29.aspx
解决方案(显而易见):
在返回语句之前移动无法访问的代码。
答案 1 :(得分:7)
无法访问的代码是编译器警告,而不是错误。您有三种选择:
无法访问,因为方法的流程在return
语句中退出,因此永远不会执行下面的代码。编译器可以确定这一点,因此可以报告它。就像我说的,这些实际上是编译器警告并且不会阻止成功构建,除非您已将项目配置为将警告视为错误。
答案 2 :(得分:5)
return count; // here you exit this method
String answer = GetAnswer(); // so you'll never get here
Response.Write(lblAntwoord);
编译器正确警告您最后一行永远不会被执行。
当你简单地将回报向下移动2行时:
String answer = GetAnswer();
Response.Write(lblAntwoord);
return count;
编译错误将消失,然后您的程序将崩溃。由你决定为什么这两种方法不应该相互调用。
答案 3 :(得分:2)
声明:
return count;
退出该功能。因此,
answer = GetAnswer();
Response.Write(lblAntwoord);
无法联系到。
答案 4 :(得分:0)
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链接: