条件“或”运算符 (||) 执行 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 | |
 请参见
请参见
 
            
          
         
      
    
     
      
    
     
      
    
     
      
    
     
      
    
    