这是我的代码:
namespace Hello_World
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetDay(0));
Console.ReadLine();
}
static string GetDay(int DayNum)
{
string DayName;
switch (DayNum)
{
case 0:
DayName = "Sunday";
break;
}
return DayName;
}
}
}
最佳答案
为了使用变量的值,您需要确保无论执行采用哪种路径,您的变量都将收到一个值。实际上,您没有保证,因为执行可能会采用一条路径,并且您的变量将不会获得任何值。那是当它不在开关盒中时,这是一个可选路径。
另外,此验证未考虑语义。例:
int a;
int b = 1;
if (b == 1) {
a = 2;
}
return a; // This causes an error
尽管执行将始终输入if,但
b
始终等于1,因此ifs始终被视为可选代码块,因此不能保证a
会及时获得return
的值。