【发布时间】:2014-10-20 17:00:30
【问题描述】:
请在下面找到我的示例程序,
根据我的输入,条件 3 不应该为真。但它返回 true 并且 if 内部的语句正在执行。帮助我更好地理解这一点。
static void Main(string[] args) {
string temp = null;
string temp1 = "0";
string temp2 = "1";
if (temp1 == "0" || temp2 == "2" && temp == null) {
Console.WriteLine("Contion 1 satisfied");
}
if (temp1 == "0" || temp2 == "1" && temp == null) {
Console.WriteLine("Contion 2 satisfied");
}
if (temp1 == "0" || temp2 == "1" && temp != null) {
Console.WriteLine("Contion 3 satisfied");
}
if (temp1 == "1" || temp2 == "1" && temp != null) {
Console.WriteLine("Contion 4 satisfied");
}
Console.ReadLine();
}
提前致谢
【问题讨论】:
-
&& 运算符的优先级高于 ||运算符
-
提示:当我组合布尔运算符(AND 和 OR)时,我不想记住哪个在前,我总是使用括号。
-
@IVAAAN123: 但
temp为空。 -
@TimSchmelter 那又怎样?真 ||假 => 真
-
括号是你的朋友
temp1 || (temp2 && temp),除了产生正确的结果,它还可以在阅读你的代码时引入清晰