跳過到頁腳內容
.NET幫助

C# 邏輯運算符(開發者的工作原理)

理解邏輯運算子在程式設計中的條件語句中是必備的。 從 XOR 到算術運算,它們在決定給定條件的真值中發揮著重要作用。

這個指南將指導您掌握 C# 中邏輯運算子的基礎知識,包括布林值、運算子的優先順序、邏輯否定等概念。

什麼是邏輯運算子?

邏輯運算子,通常稱為邏輯運算,是程式設計中決策的核心。 它們對布林表達式進行操作,根據提供的條件將其評估為 true 或 false 的布林值。 這些運算子在控制程序流程方面發揮關鍵作用,允許您根據特定標準執行特定的代碼塊。

下方我們會深入探討 C# 中不同的邏輯運算子,了解它們的功能並展示如何將邏輯運算子整合進應用程式中以精確高效地執行邏輯操作。

C# 中的邏輯運算子的類型

邏輯 AND 運算子 (&&)

邏輯 AND 運算子 (&&) 將兩個布林表達式結合起來,若兩者都為 true 則返回 true。 如果其中一個或兩個為 false,則結果為 false。 常用於必須同時滿足所有條件的多條件場景。 例如,驗證用戶是否具有足夠的年齡和足夠的餘額以進行購買。

&& 運算子:

  • 評估左操作數
  • 如果左操作數為 false,整個表達式為 false
  • 如果左操作數為 true,則評估右操作數
  • 如果兩個操作數都為 true,表達式為 true

如果左操作數為 false,則不會評估右操作數,因為整個表達式保證是 false。

class Program
{
    static void Main(string[] args)
    {
        bool isAdult = true;
        bool hasBalance = false;
        bool canPurchase = isAdult && hasBalance;

        // Output the result to the console; expected output is false
        Console.WriteLine(canPurchase); // Output: false
    }
}
class Program
{
    static void Main(string[] args)
    {
        bool isAdult = true;
        bool hasBalance = false;
        bool canPurchase = isAdult && hasBalance;

        // Output the result to the console; expected output is false
        Console.WriteLine(canPurchase); // Output: false
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim isAdult As Boolean = True
		Dim hasBalance As Boolean = False
		Dim canPurchase As Boolean = isAdult AndAlso hasBalance

		' Output the result to the console; expected output is false
		Console.WriteLine(canPurchase) ' Output: false
	End Sub
End Class
$vbLabelText   $csharpLabel

在此範例中,儘管 isAdult 為 true,但 hasBalance 為 false,所以結果為 false。

邏輯 OR 運算子 (

邏輯 OR 運算子 (||) 將兩個布林表達式結合起來,若至少有一個為 true 則返回 true。 如果兩者都為 false,則結果為 false。 理想用於至少有一個條件為 true 的場景。 例如,允許某人進入如果他是會員或持有票。

|| 運算子:

  • 評估左操作數
  • 如果左操作數為 true,整個表達式為 true
  • 如果左操作數為 false,則評估右操作數
  • 如果任一操作數為 true,則表達式為 true

如果左操作數為 true,就不會評估右操作數,因為整個表達式保證是 true。

class Program
{
    static void Main(string[] args)
    {
        bool isMember = true;
        bool hasTicket = false;
        bool canEnter = isMember || hasTicket;

        // Output the result to the console; expected output is true
        Console.WriteLine(canEnter); // Output: true
    }
}
class Program
{
    static void Main(string[] args)
    {
        bool isMember = true;
        bool hasTicket = false;
        bool canEnter = isMember || hasTicket;

        // Output the result to the console; expected output is true
        Console.WriteLine(canEnter); // Output: true
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim isMember As Boolean = True
		Dim hasTicket As Boolean = False
		Dim canEnter As Boolean = isMember OrElse hasTicket

		' Output the result to the console; expected output is true
		Console.WriteLine(canEnter) ' Output: true
	End Sub
End Class
$vbLabelText   $csharpLabel

在此處,因為 isMember 為 true,所以 hasTicket 沒有被評估,而結果為 true。

邏輯 NOT 運算子 (!)

邏輯 NOT 運算子 (!) 反轉布林表達式的值。 如果操作數為 true,則結果為 false,反之亦然。 常用於逆轉條件。 例如,如果某功能已啟用,您可能會使用 NOT 運算子來確定是否應該禁用它。

其工作原理如下:

  • 評估操作數。
  • 如果操作數為 true,則結果為 false。
  • 如果操作數為 false,則結果為 true。
class Program
{
    static void Main(string[] args)
    {
        bool isLoggedOn = false;
        bool showLoginButton = !isLoggedOn;

        // Output the result to the console; expected output is true
        Console.WriteLine(showLoginButton); // Output: true
    }
}
class Program
{
    static void Main(string[] args)
    {
        bool isLoggedOn = false;
        bool showLoginButton = !isLoggedOn;

        // Output the result to the console; expected output is true
        Console.WriteLine(showLoginButton); // Output: true
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim isLoggedOn As Boolean = False
		Dim showLoginButton As Boolean = Not isLoggedOn

		' Output the result to the console; expected output is true
		Console.WriteLine(showLoginButton) ' Output: true
	End Sub
End Class
$vbLabelText   $csharpLabel

此處,由於 isLoggedOn 為 false,邏輯 NOT 運算子返回 true。

與其他運算子結合使用

NOT 運算子可以與 AND 和 OR 運算子結合使用以創建更複雑的條件。

bool isWeekend = false;
bool hasVacation = true;
bool isWorkDay = !(isWeekend || hasVacation);

// Output the result to the console; expected output is false
Console.WriteLine(isWorkDay); // Output: false
bool isWeekend = false;
bool hasVacation = true;
bool isWorkDay = !(isWeekend || hasVacation);

// Output the result to the console; expected output is false
Console.WriteLine(isWorkDay); // Output: false
Dim isWeekend As Boolean = False
Dim hasVacation As Boolean = True
Dim isWorkDay As Boolean = Not (isWeekend OrElse hasVacation)

' Output the result to the console; expected output is false
Console.WriteLine(isWorkDay) ' Output: false
$vbLabelText   $csharpLabel

邏輯 XOR 運算子 (^)

邏輯 XOR 運算子 (^) 如果兩個操作數有不同的值,則返回 true。 如果它們都是一樣的,則返回 false。 當您想確保兩個條件中只有一個為 true 而不是同時為真時,這個運算子特別有用。

class Program
{
    static void Main(string[] args)
    {
        bool hasPassword = true;
        bool hasSmartCard = false;
        bool canLogin = hasPassword ^ hasSmartCard;

        // Output the result to the console; expected output is true
        Console.WriteLine(canLogin); // Output: true
    }
}
class Program
{
    static void Main(string[] args)
    {
        bool hasPassword = true;
        bool hasSmartCard = false;
        bool canLogin = hasPassword ^ hasSmartCard;

        // Output the result to the console; expected output is true
        Console.WriteLine(canLogin); // Output: true
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim hasPassword As Boolean = True
		Dim hasSmartCard As Boolean = False
		Dim canLogin As Boolean = hasPassword Xor hasSmartCard

		' Output the result to the console; expected output is true
		Console.WriteLine(canLogin) ' Output: true
	End Sub
End Class
$vbLabelText   $csharpLabel

由於 hasPasswordhasSmartCard 的值不同,邏輯 XOR 返回 true。 如果兩者為真或兩者為假,則返回 false。

其他相關運算子

複合賦值運算子

複合賦值運算子將算術運算與賦值結合起來。 它們是執行運算並將結果賦值給變量的簡寫。 以下是一些類型的複合賦值運算子:

  • +=: 加並賦值
  • -=: 減並賦值
  • *=: 乘並賦值
  • /=: 除並賦值
  • %=: 取模並賦值
  • &=: 按位 AND 並賦值
  • |=: 按位 OR 並賦值
  • ^=: 按位 XOR 並賦值

以下是它們的使用範例:

int x = 5;
x += 3; // Equivalent to x = x + 3; x is now 8
int x = 5;
x += 3; // Equivalent to x = x + 3; x is now 8
Dim x As Integer = 5
x += 3 ' Equivalent to x = x + 3; x is now 8
$vbLabelText   $csharpLabel

算術運算子

算術運算子執行標準的數學運算。 它們包括:

  • +: 加法
  • -: 減法
  • *: 乘法
  • /: 除法
  • %: 取模(除法的餘數)

運算子的優先順序

運算子的優先順序定義了在表達式中運算的執行順序。 例如,乘法和除法先於加和減。

以下是 C# 中運算子的優先順序:

  1. 邏輯 NOT (!)
  2. 乘法 (*, /, %)
  3. 加法 (+, -)
  4. 關係和類型測試 (<, >, <=, >=, is, as)
  5. 等號 (==, !=)
  6. 邏輯 AND (&&)
  7. 邏輯 OR (||)

按位運算子

除去對布林值進行操作的邏輯運算子外,還有一些按位邏輯運算子對整數的二進制表示進行操作。 按位邏輯運算子的類型有:

  • &: 按位 AND
  • |: 按位 OR
  • ^: 按位 XOR
  • ~: 按位 NOT
  • <<: 左移
  • >>: 右移

這些按位運算子允許您操作整數值中的個別位。

Iron Suite: 一個強大的 C# 工具包

Iron Suite for C# Development 是一組專為擴展 C# 程式設計功能而設計的庫集合。 這個非凡的工具集可以幫助開發人員在文件處理、數據處理和文本識別等廣泛的任務中。 讓我們來探索每個產品如何利用邏輯運算子。

IronPDF

IronPDF 允許開發人員在 C# 應用程式中創建、讀取、編輯和轉換 PDF 文檔。 假設您必須根據某些條件過濾和提取 PDF 中的特定信息。 可以使用邏輯運算子來定義這些條件,使程序能夠智能地決定要提取或操作的數據。

了解 IronPDF 如何增強 PDF 文檔處理

IronXL

IronXL 簡化了 Microsoft Excel 文件的工作,允許您在 C# 中直接讀寫和操作電子表格。 您可以使用邏輯運算子創建動態條件以處理數據。 例如,使用邏輯 AND 運算子過濾符合多個標準的記錄,或使用邏輯 OR 運算子選擇符合多個條件的行。

了解使用 IronXL 處理 Excel 的更多信息

IronOCR

IronOCR 是一個強大的工具,使您的 C# 應用程式能夠識別和讀取圖像中的文本。 邏輯運算子可以在提取文本後處理時發揮作用。 想像一下某個用例,您需要驗證提取的信息。 使用邏輯 NOT、AND、OR 運算子,您可以創建復雜的驗證規則以確保數據的準確性。

查看 IronOCR 如何進行光學字符識別

IronBarcode

IronBarcode 增強了在 C# 應用程式中生成、讀取和識別條形碼的能力。 您可以使用邏輯運算子來決定根據特定條件生成或讀取哪種類型的條形碼,或者根據某些邏輯規則來驗證條形碼數據。

了解 IronBarcode 如何管理條形碼操作

結論

邏輯運算子是所有新手程式設計師必備的技能,本指南僅僅是對 C# 運算子可做之事的品嚐。 在 Iron Suite for C# Development 中,您可以看到一些實際應用中使用邏輯運算子的練習。

如果您想練習 C# 技能,Iron Suite 中的每個產品在開發環境中完全免費使用。 無論您是剛起步還是已經是 C# 專家,這些工具都可以幫助您將編程水平提升到下一個階段。

常見問題解答

什麼是 C# 的邏輯運算符,它們如何被使用?

C# 中的邏輯運算符用於評估布林表達式以在編程中做出決策。包括 AND (&&)、OR (||)、NOT (!) 和 XOR (^)。這些運算符幫助確定代碼中條件的真實性,從而有效控制程式流程。

如何使用邏輯運算符處理 C# 中的 PDF 文檔?

使用 IronPDF,邏輯運算符可以定義從 PDF 文件中提取特定數據的條件。例如,您可以使用 AND (&&) 運算符確保在處理或提取數據之前滿足多個條件。

C# 中的邏輯 AND 和邏輯 OR 運算符有什麼區別?

邏輯 AND 運算符 (&&) 只有在兩個操作數都為真時才返回真,而邏輯 OR 運算符 (||) 則是在至少有一個操作數為真時返回真。這些運算符有助於構建複雜的條件語句。

邏輯 NOT 運算符如何影響 C# 中的布林表達式?

邏輯 NOT 運算符 (!) 反轉布林表達式的值。如果條件為真,則應用 NOT 運算符將其變為假,反之亦然。這對於反轉條件結果非常有用。

邏輯運算符可以與 C# 的複合賦值運算符結合使用嗎?

是的,邏輯運算符可以與 C# 的複合賦值運算符結合使用,以高效地執行操作。複合賦值運算符如 +=、-= 等允許您在一個步驟中執行算術操作並分配結果。

運算符優先級如何影響 C# 表達式的評估?

運算符優先級決定表達式中操作執行的順序。在 C# 中,乘法和除法比加法和減法先進行評估,而邏輯運算符具有其自己的優先級別,這會影響複雜表達式如何解決。

什麼是 XOR 運算符,何時在 C# 中使用?

C# 中的 XOR 運算符 (^) 在兩個操作數具有不同布林值時返回真。它特別適合需要兩個條件中只有一個為真的情況,如切換狀態。

開發者如何利用 Iron Suite 增強 C# 的文檔處理能力?

開發者可利用 Iron Suite 增強 C# 的文檔處理能力,使用工具如 IronPDF 處理 PDF、IronXL 處理 Excel 文件以及 IronOCR 進行文本識別。這些工具可與邏輯運算符整合,以高效處理數據。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。