C# 条件逻辑运算符

 x&&y对应于操作x&y,不同的是:如果x为false,则不计算y(因为不论y为何值,与操作的结果都为false)。这被称作为“短路”计算。  

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace LuoJi
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             Console.WriteLine("regular   AND:");
13             Console.WriteLine("result   is   {0}", fn1() & fn2());
14             Console.WriteLine("short-circuit   AND:");
15             Console.WriteLine("result   is   {0}", fn1() && fn2());
16 
17             Console.WriteLine("regular   OR:");
18             Console.WriteLine("result   is   {0}", fn1() | fn2());
19             Console.WriteLine("short-circuit   OR:");
20             Console.WriteLine("result   is   {0}", fn1() || fn2());   
21 
22         }
23         static bool fn1()
24         {
25             Console.WriteLine("fn1   called");
26             return false;
27         }
28 
29         static bool fn2()
30         {
31             Console.WriteLine("fn2   called");
32             return true;
33         }   
34 
35     }
36 }

 

运算结果:

regular   AND:
fn1   called
fn2   called
result   is   False
short-circuit   AND:
fn1   called
result   is   False
regular   OR:
fn1   called
fn2   called
result   is   True
short-circuit   OR:
fn1   called
fn2   called
result   is   True
请按任意键继续. . .

posted @ 2010-05-18 16:08  SoLo.  阅读(370)  评论(0)    收藏  举报