這四個邏輯運算符,大家都知道,但是有時候會凌亂,這里用程序來解釋一下,以免忘了。(根據大家反應說:這文章沒有解釋清楚它們的區別、用法,其實文章主要說的是,如果將這四個運算符用於條件判斷,那么它們會是什么結果,寫文章的初衷不是講它們的本質)
1.邏輯與
&&和&翻譯成中文就是“且”的意思,都是當兩個條件同時成立時執行,既然是這樣,為什么要兩個呢,一起來看下它們的區別,直接上代碼:
public void fun() { int c = 0; int d = 0; if ((c = 10) < d && (d = 10) <= c)//在條件語句中給變量賦值,方便觀察條件是否有執行,不要被這個給弄亂了,其實就是先賦值后判斷 { Console.WriteLine("&& c={0},d={1}", c, d); } Console.WriteLine("&& c={0},d={1}", c, d); Console.WriteLine("---------------------------------"); int e = 0; int f = 0; if ((e = 10) < f & (f = 10) <= e) { Console.WriteLine("& e={0},f={1}", e, f); } Console.WriteLine("& e={0},f={1}", e, f); }
會是什么個結果呢?大家看圖:
結論是:“&&”當從左到右有條件為false時,就直接跳出if語句,不再往下判斷,所以程序中的d不會被賦值;而“&”是無論從左到右的條件是不是為true,都會執行所有的判斷條件,所以程序中的f會被賦值為10。
2.邏輯或
||和|翻譯成中文就是“或”的意思,都是當兩個條件中至少有一個成立時執行,一起來看下它們的區別,直接上代碼:
private void fun() { int x = 0; int y = 0; if ((x = 10) > y || (y = 10) < x) { Console.WriteLine("|| x={0},y={1}", x, y); } Console.WriteLine("---------------------------------"); int a = 0; int b = 0; if ((a = 10) > b | (b = 10) < a) { Console.WriteLine("| a={0},b={1}", a, b); } }
直接看結果圖:
結論是:“||”當有一個條件成立時,就不再往下執行判斷條件而直接執行if的內容,所以程序中的y不會被賦值為10;“|”從左到右無論是否有條件成立,都會將所有的判斷語句執行。
附上本實例完整代碼,以便大家體驗,建立個控制台應用程序復制黏貼,直接用:
static void Main(string[] args) { int x = 0; int y = 0; if ((x = 10) > y || (y = 10) < x) { Console.WriteLine("|| x={0},y={1}", x, y); } Console.WriteLine("---------------------------------"); int a = 0; int b = 0; if ((a = 10) > b | (b = 10) < a) { Console.WriteLine("| a={0},b={1}", a, b); } Console.WriteLine("---------------------------------"); int c = 0; int d = 0; if ((c = 10) < d && (d = 10) <= c) { Console.WriteLine("&& c={0},d={1}", c, d); } Console.WriteLine("&& c={0},d={1}", c, d); Console.WriteLine("---------------------------------"); int e = 0; int f = 0; if ((e = 10) < f & (f = 10) <= e) { Console.WriteLine("& e={0},f={1}", e, f); } Console.WriteLine("& e={0},f={1}", e, f); Console.ReadKey(); }
總結:一句話概括——當是兩個運算符(&&,||)時,當第一個條件成立(||)或違反(&&),就不再繼續判斷之后的條件,所以效率高一點;當是一個運算符(&,|)時,無論第一個條件是否成立(|)或違法(&),都會繼續執行剩下的判斷語句,所以效率低一點。