C# 中 | 和 || 運算子有什麼區別?
|| 稱為**邏輯或**運算子,而 | 稱為**按位邏輯或**運算子,但它們之間最基本的區別在於執行方式。|| 和 | 的語法如下所示:
- bool_exp1 || bool_exp2
- bool_exp1 | bool_exp2
- 現在,1 和 2 的語法看起來很相似,但它們的執行方式完全不同。
- 在第一個語句中,首先執行 bool_exp1,然後根據該表示式的結果決定是否執行另一個語句。
- 如果它是真,則或運算結果為真,因此執行另一個語句毫無意義。
- 只有當 bool_exp1 執行後返回假時,才會執行 bool_exp2 語句。
- 它也稱為短路運算子,因為它根據第一個表示式的結果來“短路”(語句)。
- 現在,對於 |,情況有所不同。編譯器將執行這兩個語句,換句話說,無論一個語句的結果如何,都會執行這兩個語句。
- 這是一種低效的做法,因為如果一個語句為真,則執行另一個語句毫無意義,因為或運算的結果僅對評估為“假”的結果有效,而這隻有當兩個語句都為假時才有可能。
邏輯或
示例
using System; namespace DemoApplication{ public class Program{ static void Main(string[] args){ if(Condition1() || Condition2()){ Console.WriteLine("Logical OR If Condition Executed"); } Console.ReadLine(); } static bool Condition1(){ Console.WriteLine("Condition 1 executed"); return true; } static bool Condition2(){ Console.WriteLine("Condition 2 executed"); return true; } } }
輸出
Condition 1 executed Logical OR If Condition Executed
按位邏輯或
示例
using System; namespace DemoApplication{ public class Program{ static void Main(string[] args){ if(Condition1() | Condition2()){ Console.WriteLine("Logical OR If Condition Executed"); } Console.ReadLine(); } static bool Condition1(){ Console.WriteLine("Condition 1 executed"); return true; } static bool Condition2(){ Console.WriteLine("Condition 2 executed"); return true; } } }
輸出
Condition 1 executed Condition 2 executed Logical OR If Condition Executed
廣告