&运算符
& 运算符既可作为一元运算符也可作为二元运算符。
一元 & 运算符返回操作数的地址(要求 unsafe 上下文)。
为整型和 bool
类型预定义了二进制 & 运算符。 对于整型,& 计算操作数的逻辑按位“与”。 对于 bool
操作数,& 计算操作数的逻辑“与”;也就是说,当且仅当两个操作数均为 true
时,结果才为 true
。
&
运算符计算两个运算符,与第一个操作数的值无关。 例如:
int i = 0; if (false & ++i == 1) { // i is incremented, but the conditional // expression evaluates to false, so // this block does not execute. }
用户定义的类型可重载二元 &
运算符(请参见 operator)。 在枚举时通常允许整型运算。 重载二元运算符时,也会隐式重载相应的赋值运算符(如果有)。
class BitwiseAnd { static void Main() { // The following two statements perform logical ANDs. Console.WriteLine(true & false); Console.WriteLine(true & true); // The following line performs a bitwise AND of F8 (1111 1000) and // 3F (0011 1111). // 1111 1000 // 0011 1111 // --------- // 0011 1000 or 38 Console.WriteLine("0x{0:x}", 0xf8 & 0x3f); } } // Output: // False // True // 0x38
备注:转自https://msdn.microsoft.com/zh-cn/library/sa7629ew.aspx
*********************************************
&&运算符
条件“与”运算符 (&&
) 执行其 bool
操作数的逻辑“与”运算,但仅在必要时才计算第二个操作数。
操作
x && y
对应于操作
x & y
,但,如果 x
是 false
, y
不会计算,因为,和操作的结果是 false
,无论 y
的值为。 这被称作为“短路”计算。
不能重载条件“与”运算符,但常规逻辑运算符和运算符 true 与 false 的重载,在某些限制条件下也被视为条件逻辑运算符的重载。
在下面的示例中,,因为该操作数返回 false
,在第二个 if
语句的条件表达式计算只有第一个操作数。
class LogicalAnd { static void Main() { // Each method displays a message and returns a Boolean value. // Method1 returns false and Method2 returns true. When & is used, // both methods are called. Console.WriteLine("Regular AND:"); if (Method1() & Method2()) Console.WriteLine("Both methods returned true."); else Console.WriteLine("At least one of the methods returned false."); // not called. Console.WriteLine("\nShort-circuit AND:"); if (Method1() && Method2()) Console.WriteLine("Both methods returned true."); else Console.WriteLine("At least one of the methods returned false."); } static bool Method1() { Console.WriteLine("Method1 called."); return false; } static bool Method2() { Console.WriteLine("Method2 called."); return true; } } // Output: // Regular AND: // Method1 called. // Method2 called. // At least one of the methods returned false. // Short-circuit AND: // Method1 called. // At least one of the methods returned false.
备注:转自https://msdn.microsoft.com/zh-cn/library/2a723cdk.aspx
转载于:https://blog.51cto.com/jiaojusuimu/1885040