In what a case won't this function return a value? Why does the compiler report an error?
public static int Test(int n)
{
if (n 开发者_StackOverflow社区< 0) return 1;
if (n == 0) return 2;
if (n > 0) return 3;
}
Compiler (Visual Studio 2010, C# 4.0) says "Not all code paths return a value". Why?
The compiler doesn't try to determine that this covers all the possible values of n
. All it sees is that you have three if
statements, and it assumes that it's possible for all of them to be false... in which case you'd reach the end of the method without returning a value.
See this blog post from Eric Lippert for more details about the compiler's limits when it comes to reachability.
Just make the final return unconditional.
The compiler isn't looking at your conditions. Even though you are correct that at least one of your if-blocks will run, you still need to refactor to something like this:
if (n < 0)
return 1;
else if (n == 0)
return 2;
else
return 3;
The compiler isn't smart enough to know that all of those branches are mutually exclusive, so it worries about the fallthrough case where all three if statements fail.
You can either link all the if
statements with else
and use only else
for the last condition, or you can return a default value at the end. This will get around the issue.
The compiler doesn't know you've covered all your bases. You can rewrite it like this...
public static int Test(int n)
{
if (n < 0) return 1;
else if (n == 0) return 2;
else (n > 0) return 3;
}
or this...
public static int Test(int n)
{
if (n < 0) return 1;
if (n == 0) return 2;
if (n > 0) return 3;
return 4; //will never occur
}
精彩评论