有没有办法告诉程序我不在乎类引用是否为空。例如:
if (playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
为什么他要搜索 playermove(可以为空)并给我一个空异常错误?我真的不在乎 ispunchactivated 是否为真。
谢谢。
如果你把你的两个条件反过来:
ispunchactivated /*== true*/ || playermove[i].name == "punch"
// this isn't necessary
那么,如果第一个为真,则不会检查第二个。
但是,除非您知道 playermove[i]
如果为 false 不会为 null ,否则ispunchactivated
您确实应该也进行 null 检查,否则您仍然会遇到异常:
ispunchactivated ||
(playermove[i] != null && playermove[i].name == "punch")
您只需先检查它是否为空。
这里没有捷径。
if (playermove == null || playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
您可以按如下方式修改 if 条件:
if (ispunchactivated == true || (playermove!=null && playermove[i].name == "punch" ))
尝试这个,
if ((ispunchactivated == true) || (playermove[i] != null && playermove[i].name == "punch" ))
{
Do the punch;
}
只需交换条件,短路就会为您做到这一点:
if (ispunchactivated == true || playermove[i].name == "punch")
{
Do the punch;
}
playermove[i]
仅在ispunchactivated
为 false 时评估。ispunchactivated
话虽如此,如果为假且为空,您仍然可以遇到空指针异常playermove[i]
。
改变你的条件如下:
if(playermove !=null && playermove[i] != null)
{
if (playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
}