程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> AndAlso & OrElse Operators in C#短路運算符

AndAlso & OrElse Operators in C#短路運算符

編輯:.NET實例教程
AndAlso(&&)
輯運算符 AndAlsoOrElse 表現稱為“短路”的行為。短路運算符首先計算左側表達式。如果左側表達式使整個表達式為假(在 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. below
int 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 below
int 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");
}

//OrElse
if (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.
 
 
  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved