共用方式為


&& 運算子 (C# 參考)

AND 條件運算子 (&&) 會對其 bool 運算元執行 AND 邏輯運算,但只有在需要時才會評估第二個運算元。

備註

運算

x && y

對應到這項運算

x & y

但是,如果x 是false, y則不評估,因為 AND 運算的結果是false無論何種值的y 是。 這就是所謂的「最少運算」(Short-Circuit) 評估。

AND 條件運算子無法多載,但是在特定限制下,標準邏輯運算子與 truefalse 運算子的多載,也視為條件邏輯運算子的多載。

範例

在下列範例中,在第二個條件式運算式if陳述式只評估了第一個運算元運算元回傳因為false。

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# 參考