& 运算符既可作为一元运算符也可作为二元运算符。
备注
一元 & 运算符返回操作数的地址(要求 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)。在枚举时通常允许整型运算。重载二元运算符时,也会隐式重载相应的赋值运算符(如果有)。
示例
![]() | |
---|---|
// cs_operator_ampersand.cs using System; class MainClass { static void Main() { Console.WriteLine(true & false); // logical and Console.WriteLine(true & true); // logical and Console.WriteLine("0x{0:x}", 0xf8 & 0x3f); // bitwise and } } |
输出
False True 0x38 |
请参见
