“&”和“&&”的区别
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class LogicalAnd { static bool Method1() { Console.WriteLine("Method1 called"); return false; }
static bool Method2() { Console.WriteLine("Method2 called"); return true; }
static void Main() { Console.WriteLine("regular AND:"); Console.WriteLine("result is {0}", Method1() & Method2()); Console.WriteLine("short-circuit AND:"); Console.WriteLine("result is {0}", Method1() && Method2()); } } /* Output: regular AND: Method1 called Method2 called result is False short-circuit AND: Method1 called result is False */ |
由上面的例子我们可以清楚的看到。当使用“&”时,程序会将两个操作数都进行计算后然后得出结果,而“&&”当第一个操作数是false的时候,就没有必要进行计算第二个操作数,直接得出结果false。
“|”和“||”的区别
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class ConditionalOr { static bool Method1() { Console.WriteLine("Method1 called"); return true; }
static bool Method2() { Console.WriteLine("Method2 called"); return false; }
static void Main() { Console.WriteLine("regular OR:"); Console.WriteLine("result is {0}", Method1() | Method2()); Console.WriteLine("short-circuit OR:"); Console.WriteLine("result is {0}", Method1() || Method2()); } } /* Output: regular OR: Method1 called Method2 called result is True short-circuit OR: Method1 called result is True */ |
由上面的例子我们可以清楚的看到。当使用“|”时,程序会将两个操作数都进行计算后然后得出结果,而“||”当第一个操作数是ture的时候,就没有必要进行计算第二个操作数,直接得出结果ture。
C语言的短路特性相同