C# 中的 | 和 || 或運算子有什麼區別?
| 運算子
| 運算子計算其運算元的邏輯 OR。如果 x 或 y 為真,則 x | y 的結果為真。否則,結果為假。
| 運算子即使左運算元為真也會對兩個運算元進行計算,這樣無論右運算元的值是什麼,運算結果都是真。
|| 運算子
條件邏輯 OR 運算子 ||,也稱為“短路”邏輯 OR 運算子,計算其運算元的邏輯 OR。
如果 x 或 y 為真,則 x || y 的結果為真。否則,結果為假。如果 x 為真,則不計算 y。
示例
class Program {
static void Main(string[] args){
int a = 4;
int b = 3;
int c = 0;
c = a | b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
Console.ReadLine();
}
}輸出
Value of c is 7 Here the values are converted to binary 4−−100 3−−011 Output 7 −−111
示例 2
static void Main(string[] args){
int a = 4;
int b = 3;
int c = 7;
if (a > b || b > c){
System.Console.WriteLine("a is largest");
} else {
System.Console.WriteLine("a is not largest");
}
Console.ReadLine();
}輸出
a is largest
在上述示例中,其中一個條件返回真,因此不再檢查下一個條件。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP