我收到编译时错误
'UserQuery.ReturnInt(UserQuery.Foo)':并非所有代码路径都返回一个值
除非我在代码中没有看到某些内容,否则switch语句应该返回0作为默认值,因此所有代码路径都返回一个值.
enum Foo
{
Bar,
Zoo,
Boo
}
void Main()
{
Foo test = Foo.Bar;
Console.WriteLine (ReturnInt(test));
}
int ReturnInt(Foo test) {
int someOtherValue = 4; // <---Value may change depending on X
switch (test)
{
case Foo.Bar:
if (someOtherValue > 20)
return 1;
break;
case Foo.Zoo:
if (someOtherValue == 5)
return 4;
break;
case Foo.Boo:
if (someOtherValue == 2)
return 7;
break;
default:
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
我会改变它,以便只有一个返回点,无论如何我为了清晰的原因而喜欢它.:-)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static int ReturnInt(Foo test)
{
int retVal = 0; // defaults to 0
int someOtherValue = 4; // <---Value may change depending on X
switch (test)
{
case Foo.Bar:
if (someOtherValue > 20)
retVal = 1;
break;
case Foo.Zoo:
if (someOtherValue == 5)
retVal = 4;
break;
case Foo.Boo:
if (someOtherValue == 2)
retVal = 7;
break;
default:
retVal = 0;
break;
}
return retVal;
}
enum Foo
{
Bar,
Zoo,
Boo
}
static void Main(string[] args)
{
Foo test = Foo.Bar;
Console.WriteLine(ReturnInt(test));
}
}
}
Run Code Online (Sandbox Code Playgroud)