標籤:style blog http color ar strong 2014 div sp
這四個邏輯運算子,大家都知道,但是有時候會淩亂,這裡用程式來解釋一下,以免忘了。
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(); }
總結:一句話概括——當是兩個運算子(&&,||)時,當第一個條件成立(||)或違反(&&),就不再繼續判斷之後的條件,所以效率高一點;當是一個運算子(&,|)時,無論第一個條件是否成立(|)或違法(&),都會繼續執行剩下的判斷語句,所以效率低一點。
邏輯與(&&、&)和邏輯或(||、|)