如何解决此错误“并非所有代码路径都返回值”

时间:2013-05-22 06:37:13

标签: c# visual-studio-2010

setSpeedX标有“不是所有代码路径都返回值”的错误。我可以知道如何解决它吗?代码如下:

class Ball
{
    public int speedX { get; private set; }
    public int speedY { get; private set; }
    public int positionX { get; private set; }
    public int positionY { get; private set; }

    public Ball(int speedX, int speedY, int positionX, int positionY)
    {
        this.speedX = speedX;
        this.speedY = speedY;
        this.positionX = positionX;
        this.positionY = positionY;
    }

    public int setSpeedX(int newSpeedX)
    {
        speedX = newSpeedX;
    }    

    public int setSpeedY(int newSpeedY)
    {
        speedY = newSpeedY;
    }

    public int setPositionX(int newPositionX)
    {
        positionX = newPositionX;
    }

    public int setPositionY(int newPositionY)
    {
        positionY = newPositionY;
    }
}

谢谢。

4 个答案:

答案 0 :(得分:3)

return添加到应返回值的方法中,如:

public int setPositionY(int newPositionY)
{
    positionY = newPositionY;
    return positionY;
}

或更改它们以返回void

public void setPositionY(int newPositionY)
{
    positionY = newPositionY;
}

答案 1 :(得分:1)

你永远不会输入return语句,所以即使你声明了它应该的方法,也不会返回任何值。

有两种方法可以解决这个问题:

制作方法void

public void setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
}

或返回一个值:

public int setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
    return speedX;
}

顺便说一句,这适用于所有方法,而不仅仅是setSpeedX

答案 2 :(得分:0)

您在方法中设置了一个值(setSpeedXsetSpeedYsetPositionXsetPositionY),但没有返回任何内容。但是方法的签名具有返回类型int

所以......用int替换返回类型void,如下所示:

public void setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
}    

public void setSpeedY(int newSpeedY)
{
    speedY = newSpeedY;
}

public void setPositionX(int newPositionX)
{
    positionX = newPositionX;
}

public void setPositionY(int newPositionY)
{
    positionY = newPositionY;
}

或返回类型int的值,如下所示:

public int setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
    return speedX;
}    

public int setSpeedY(int newSpeedY)
{
    speedY = newSpeedY;
    return speedY;
}

public int setPositionX(int newPositionX)
{
    positionX = newPositionX;
    return positionX;
}

public int setPositionY(int newPositionY)
{
    positionY = newPositionY;
    return positionY;
}

答案 3 :(得分:0)

返回值

public int setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
    return(speedX);
}

或者将方法更改为无效

public void setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
}

返回值似乎没什么价值