方法中发生“并非所有代码路径都返回值”错误,但是我确实使用了一些if语句来覆盖所有情况 [英] “not all code path return a value” error occurs in a method, but I did use some if statements to cover all scenario

查看:90
本文介绍了方法中发生“并非所有代码路径都返回值”错误,但是我确实使用了一些if语句来覆盖所有情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我只想让一个人给出更好的解释。



我有如下定义的方法:

  private int Test(int i)
{
如果(i< 0)返回-1;
如果(i == 0)返回0;
如果(i> 0)返回1;

//返回0;
}

它给了我这个错误并非所有代码路径都返回值。 / p>

我以为我有3个 if语句,它可以涵盖所有情况(i <0,i == 0 ,i> 0)。因此,它不应向我显示此错误。

解决方案

编译器不是那么聪明。另外,您的代码效率不高,因为它会测试确定性( i 在最后一种情况下必须大于零)。



写为:

  private int Test(int i)
{
如果(i <0)返回-1;
else if(i == 0)返回0;
否则返回1;
}


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.

解决方案

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;
}

这篇关于方法中发生“并非所有代码路径都返回值”错误,但是我确实使用了一些if语句来覆盖所有情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆