问题
This may be a stupid question, but I just want to somebody can give a better explanation.
I have a method defined as below:
private int Test(int i)
{
if (i < 0) return -1;
if (i == 0) return 0;
if (i > 0) return 1;
//return 0;
}
It gives me this error "not all code path return a value".
I thought I had 3 if statement
, which could cover all the scenarios(i<0, i==0, i>0). So it should not show me this error.
回答1:
The compiler just ain't that clever. Also, you're code is slightly inefficient in that it tests for a certainty (i
must be greater than zero in the last case).
Write it as:
private int Test(int i)
{
if (i < 0) return -1;
else if (i == 0) return 0;
else return 1;
}
回答2:
During compile-time, the compiler doesn't analyze the conditions and understands that they cover all the options - it just sees three unrelated if
statements, and a path with no return
if none of them are triggered.
You can make it "understand" by using else if
and else
s:
private int Test(int i)
{
if (i < 0) return -1;
else if (i == 0) return 0;
else return 1;
}
回答3:
If you want to keep your format, a way to do it is like this...
private int Test(int i)
{
bool result = 1;
if (i < 0) result = -1;
if (i == 0) result = 0;
if (i > 1) result = 1; //This is redundant because i is initialized to 1
return result;
}
来源:https://stackoverflow.com/questions/61135896/not-all-code-path-return-a-value-error-occurs-in-a-method-but-i-did-use-some