文章内容

2017/2/3 10:45:00,作 者: 黄兵

C#语言中条件与&&与条件或||的区别

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

&&:逻辑与,前后条件同时满足表达式为真 ||:逻辑或,前后条件只要有一个满足表达式为真.

具体不做详细介绍了,结合案例给大家做剖析,具体如下:

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

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

同时我们还要了解到  || 和 && 都是左结合性的逻辑运算符,所以看下面的例子

操作

x && y  

对应于操作

x & y  

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

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

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

参考:MSDN文档

分享到:

发表评论

评论列表