如何使用if语句返回此变量?

Sea*_*iss 5 c# boolean

我知道这可能是一个愚蠢的问题,答案很简单,但经过一个小时的互联网搜索,我找不到办法做到这一点;

    public bool GetCollision(int x, int y)
    {
        bool isPassable;

        if (x < 0 || x >= 20)
        {
            isPassable = false;
        }

        if (y < 0 || y >= 20)
        {
            isPassable = true;
        }

        return isPassable;
    }
Run Code Online (Sandbox Code Playgroud)

在倒数第二行,它表示isPassable是未分配的......但很明显我在if语句中分配它.我必须对"如果"的陈述有一些基本的误解.

那么,我该怎么做呢?非常感谢你.

dut*_*tzu 9

那是因为它没有明确设置默认值.默认情况下将isPassable设置为False,您就完成了.


你也可以这样做:

return (!(x < 0 || x >= 20) && (y < 0 || y >= 20))
Run Code Online (Sandbox Code Playgroud)

编辑:只有在您的IF之间存在AND关系时,上述解决方案才有效.