0

有没有办法告诉程序我不在乎类引用是否为空。例如:

if (playermove[i].name == "punch" || ispunchactivated == true)
{
    Do the punch;
}

为什么他要搜索 playermove(可以为空)并给我一个空异常错误?我真的不在乎 ispunchactivated 是否为真。

谢谢。

4

6 回答 6

9

如果你把你的两个条件反过来:

ispunchactivated /*== true*/ || playermove[i].name == "punch"
                 // this isn't necessary

那么,如果第一个为真,则不会检查第二个。

但是,除非您知道 playermove[i]如果为 false 不会为 null ,否则ispunchactivated您确实应该也进行 null 检查,否则您仍然会遇到异常:

ispunchactivated ||
    (playermove[i] != null && playermove[i].name == "punch")
于 2012-11-15T09:12:32.937 回答
4

您只需先检查它是否为空。
这里没有捷径。

if (playermove == null || playermove[i].name == "punch" || ispunchactivated == true)
{
    Do the punch;
}
于 2012-11-15T09:11:55.887 回答
3

您可以按如下方式修改 if 条件:

if (ispunchactivated == true || (playermove!=null && playermove[i].name == "punch" ))
于 2012-11-15T09:12:21.363 回答
3

尝试这个,

if ((ispunchactivated == true) || (playermove[i] != null && playermove[i].name == "punch" ))
{
    Do the punch;
}
于 2012-11-15T09:12:46.487 回答
2

只需交换条件,短路就会为您做到这一点:

if (ispunchactivated == true || playermove[i].name == "punch")
{
    Do the punch;
}

playermove[i]仅在ispunchactivated为 false 时评估。ispunchactivated话虽如此,如果为假且为空,您仍然可以遇到空指针异常playermove[i]

于 2012-11-15T09:13:11.213 回答
1

改变你的条件如下:

if(playermove !=null && playermove[i] != null)
{
    if (playermove[i].name == "punch" || ispunchactivated == true)
    {
        Do the punch;
    }
}
于 2012-11-15T09:13:41.340 回答