1、”&“的含义
对于整型,& 计算操作数的逻辑按位“与”,也就是对1/0的运算,当且仅当两个操作数都为1时,结果才为1,其它都是0;对于 bool 操作数,& 计算操作数的逻辑“与”;也就是说,当且仅当两个操作数均为 true 时,结果才为 true,其它的都是false。
例如:
int i=0;
false&++i=1//这个表达式是false,虽然++i=1是true;
2、“&&”的含义
条件“与”运算符 (&&) 执行其 bool 操作数的逻辑“与”运算,但仅在必要时才计算第二个操作数。
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。
3、“|”的含义:
对于整型, |计算操作数的按位“或”,就是对0/1,当且仅当两个操作数中的一个为1,结果就是1。 对于 bool 操作数, | 计算操作数的逻辑“或”;也就是说,当且仅当两个操作数均为 false 时,结果才为 false。
static void Main()
{
Console.WriteLine(true | false); // logical or
Console.WriteLine(false | false); // logical or
Console.WriteLine("0x{0:x}", 0xf8 | 0x3f); // bitwise or
}
/*
Output:
True
False
0xff 和与运算,“|”按位 或 运算,应该结果应该选取较大的值。
*/
4、“||”的含义
条件“或”运算符 (||) 执行 bool 操作数的逻辑“或”运算,仅在必要时才会计算第二个操作数。
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。