다음을 통해 공유


&& 연산자(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# 프로그래밍 가이드

기타 리소스

C# 참조