AndAlso(&&)
輯運算符
AndAlso 和
OrElse 表現稱為“短路”的行為。短路運算符首先計算左側表達式。如果左側表達式使整個表達式為假(在
AndAlso 中)或驗證(在
OrElse 中)整個表達式,則程序執行過程繼續,而不計算右側表達式。
同樣,如果使用
OrElse 的邏輯表達式中左側表達式計算為
True,則執行過程繼續下一行代碼,而不計算第二個表達式,因為第一個表達式已經啟用整個表達式。
AndAlso 運算符
對兩個表達式執行簡化邏輯合取。
備注
如果編譯的代碼可以根據一個表達式的計算結果跳過對另一表達式的計算,則將該邏輯運算稱為“短路”。如果第一個表達式的計算結果可以決定運算的最終結果,則不需要計算另一個表達式,因為它不會更改最終結果。如果跳過的表達式很復雜或涉及過程調用,則短路可以提高性能。
OrElse 運算符
用於對兩個表達式執行短路邏輯析取。
如果編譯的代碼可以根據一個表達式的計算結果跳過對另一表達式的計算,則將該邏輯運算稱為“短路”。如果第一個表達式的計算結果可以決定運算的最終結果,則不需要計算另一個表達式,因為它不會更改最終結果。如果跳過的表達式很復雜或涉及過程調用,則短路可以提高性能。
The logical Operator && is the AndAlso in C#. This is used to connect two logical conditions checking like if (<condition1> && <condition2>). In this situation both conditions want to be true for passing the logic. Looking at the e.g. belowint a = 100;int b = 0;if (b > 0 && a/b <100){ Console.Write("ok"); }
The point here is, the condition "b > 0" will check first. Because "b > 0" a false condition, second condition "a/b <100" won't need to check and our "&&" operator won't perform the second condition checking. So actually our execution time is saving in a logical operation in which more conditions are combined using "&&" Operator.And(&)The difference of "&" Operator compared to above is mentioned belowint a = 100;int
pan> b = 0;
if (b > 0 & a/b <100){ Console.Write("ok"); }
The point here is, the condition "b > 0" will check first. Because "b > 0" a false condition, second condition "a/b <100" won't need to check. But our "&" Operator will perform the second condition checking also. So actually our execution time is losing for a useless checking. Also executing the "a/b <100" unless b>0 is generating an error also. So got the point?Or(|) and OrElse(||)The difference of Or ("|") and OrElse ("||") are also similar to "And" Operators, as first one will check all conditions and second one won't execute remaining logical checking, if it's found any of the previous checking is true and saving time. You can analysis these by the below code.//Or if (b > 0 | a/b <100){ Console.Write("ok"); }//OrElseif (b >= 0 || a/b <100){ Console.Write("ok"); }
At last for VB.NET developers, they can use these operators by the way "AndAlso" and "OrElse". Actually VB.NET guys can use "AND" and "OR" Operators. But they are basically from VB6 and supported still by VB.Net, like many other functionalitIEs. But my advice is to use "AndAlso" and "OrElse". Because you already see some positive side of the
se Operators.