CSDN說明:
條件“或”運算符 (||) 執行 bool 操作數的邏輯“或”運算,但僅在必要時才計算第二個操作數。
件“與”運算符 (&&) 執行其 bool 操作數的邏輯“與”運算,但僅在必要時才計算第二個操作數
同時我們還要了解到 || 和 && 都是左結合性的邏輯運算符,所以看下面的例子
class Program
{
static void Main(string[] args)
{
int a = 9;
int b = 10;
int c = 11;
int d = 12;
if (d>b || c > b && a>b)
{
Console.WriteLine("true");
}
Console.ReadKey();
}
}
所以在判斷到d>b為true時,后面的部分c > b && a>b就不會再運算,進入條件語句里面
更正:
上面的結果原因是由於 && 的優先級高於 || ,所以上面的條件相當於 d>b || (c>b && a>b) 。在看一個例子
1 if ( a > b && c > b || d > b) 2 { 3 Console.WriteLine("true"); 4 }
上面這個結果也是ture,以為上面的條件相當於 (a>b && c>b) || d>b。
上面我們已經知道了&& 的優先級高於 || ,那么下面我們通過兩位一種方式看看 && 和 || 的短路特性(就是開篇CSDN說明:中說的特性)及其的結合性。
看下面的代碼
1 class Program 2 { 3 static int trueTimes = 1; 4 static int falseTimes = 1; 5 static bool GetTrue() 6 { 7 Console.WriteLine("Execute GetTrue():" + trueTimes++); 8 return true; 9 } 10 11 static bool GetFalse() 12 { 13 Console.WriteLine("Execute GetFalse():" + falseTimes++); 14 return false; 15 } 16 17 static void Main(string[] args) 18 { 19 Console.WriteLine(GetTrue() && GetTrue() || GetFalse()); 20 Console.ReadKey(); 21 22 } 23 24 25 }
輸出結果為
Execute GetTrue():1
Execute GetTrue():2
True
分析:由於&& 優先級比較高,所以條件相當於(GetTrue() && GetTrue() )|| GetFalse() ,所以執行第一個GetTrue()時,還會執行第二個GetTrue()才能確定真個表達式為真,其實對於 || 后面的方面,就會被短路,不被執行,因為前面的結果已經可以證明整個表達式為True。
我們再換個邏輯表達式
1 static void Main(string[] args) 2 { 3 Console.WriteLine(GetFalse() && GetTrue() || GetFalse()); 4 Console.ReadKey(); 5 6 }
輸出結果為
Execute GetFalse():1
Execute GetFalse():2
False
分析:由於&& 優先級比較高,所以條件相當於(GetTrue() && GetTrue() )|| GetFalse() ,所以執行第一個GetFalse()時,(GetTrue() && GetTrue() )就一定為假,所以后面的GetTrue()不會執行,被短路,這個里面我們也可以看出&& 和 || 是從左到右的結合方式,這個時候我們必須繼續執行||后面的邏輯,才能確認整個表達式是真是假,所以GetFalse會被執行。
上面是我這邊的更正,如果有錯誤或疏忽之處,望不惜賜教!