&& 运算符(C# 参考)

条件“与”运算符 (&&) 执行其 bool 操作数的逻辑“与”运算,但仅在必要时才计算第二个操作数。

备注

操作

x && y

对应于操作

x & y

,但,如果 x是 false, y 不会计算,因为,和操作的结果是 false ,无论 y 的值为。这被称作为“短路”计算。

不能重载条件“与”运算符,但常规逻辑运算符和运算符 truefalse 的重载,在某些限制条件下也被视为条件逻辑运算符的重载。

在下面的示例中,,因为该操作数返回 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.");

        // When && is used, after Method1 returns false, Method2 is 
        // 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.

C# 语言规范

有关详细信息,请参阅 C# 语言规范。该语言规范是 C# 语法和用法的权威资料。

请参阅

C# 参考

C# 编程指南

C# 运算符