& 运算符(C# 参考)

& 运算符既可作为一元运算符也可作为二元运算符。

备注

一元 & 运算符返回操作数的地址(要求 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

请参阅

C# 参考

C# 编程指南

C# 运算符