62,232
社区成员




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
*/
int i = 0;
if (false & ++i == 1)
{
// i is incremented, but the conditional
// expression evaluates to false, so
// this block does not execute.
}
string s = "Test"; // 此时 s.Length == 4
if (s.Length > 4 && s[4] == 'A') ...
// 没问题,左边的表达式为假,所以整个表达式为假,不会计算右边的表达式。
if (s.Length > 4 & s[4] == 'A') ...
// 运行时会抛出异常,索引超出数组界限,即使左边的表达式为假,仍要计算右边的表达式,导致异常。