C#的Or的短路操作

|| 运算符(C# 参考)from MSDN
条件“或”运算符 (||) 执行 bool 操作数的逻辑“或”运算,但仅在必要时才计算第二个操作数。
x || y
对应于操作
x | y
不同的是,如果 x 为 true,则不计算 y(因为不论 y 为何值,“或”操作的结果都为 true)。这被称作为“短路”计算。

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

示例
在下面的示例中,请观察使用 || 的表达式只计算第一个操作数。
// cs_operator_short_circuit_OR.cs
using System;
class MainClass
{
    static bool Method1()
    {
        Console.WriteLine("Method1 called");
        return true;
    }

    static bool Method2()
    {
        Console.WriteLine("Method2 called");
        return false;
    }

    static void Main()
    {
        Console.WriteLine("regular OR:");
        Console.WriteLine("result is {0}", Method1() | Method2());
        Console.WriteLine("short-circuit OR:");
        Console.WriteLine("result is {0}", Method1() || Method2());
    }
}
输出

regular OR:
Method1 called
Method2 called
result is True
short-circuit OR:
Method1 called
result is True
posted @ 2009-04-06 11:28  thinkpore  阅读(1133)  评论(0)    收藏  举报