.NET幫助 C# If(開發者的工作原理) Curtis Chau 更新日期:9月 1, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 在本教程中,我們將拆解if和else語句的概念,以及如何在您的C#程序中有效地使用它們。 我們還將探索相關概念,如布林表達式和條件運算符。 那麼,讓我們深入研究吧! 理解If語句 if語句是程式設計中的基本概念。 它用於基於某個條件在代碼中做出決策。 C#中if語句的基本語法如下: if (Boolean expression) { // Statements to execute if the Boolean expression is true } if (Boolean expression) { // Statements to execute if the Boolean expression is true } If Boolean expression Then ' Statements to execute if the Boolean expression is true End If $vbLabelText $csharpLabel 如果語句檢查給定的布林表達式是否評估為true。 如果是,則執行語句塊內的代碼(括號內的代碼)。 如果布林表達式評估為false,則跳過語句塊內的代碼。 If-Else語句的威力 那麼,如果您希望在if條件為假時執行其他代碼怎麼辦? 這就是選擇性的else語句發揮作用的地方。 C#中if-else語句的語法如下所示: if (Boolean expression) { // Statements to execute if the Boolean expression is true } else { // Statements to execute if the Boolean expression is false } if (Boolean expression) { // Statements to execute if the Boolean expression is true } else { // Statements to execute if the Boolean expression is false } If Boolean expression Then ' Statements to execute if the Boolean expression is true Else ' Statements to execute if the Boolean expression is false End If $vbLabelText $csharpLabel 在上述情況下,如果布林表達式評估為true,則執行if塊中的代碼。 如果它評估為false,則執行else塊中的代碼。 簡單示例 看一個使用C#if-else語句的實際例子。 想像一下,您正在編寫一個程序,用於檢查某人是否有資格投票。 在大多數國家,投票年齡為18歲。 以下示例演示如何使用if-else語句來確定投票資格: using System; class Program { static void Main(string[] args) { int age = 21; if (age >= 18) { Console.WriteLine("You are eligible to vote!"); } else { Console.WriteLine("Sorry, you are not eligible to vote."); } } } using System; class Program { static void Main(string[] args) { int age = 21; if (age >= 18) { Console.WriteLine("You are eligible to vote!"); } else { Console.WriteLine("Sorry, you are not eligible to vote."); } } } Imports System Friend Class Program Shared Sub Main(ByVal args() As String) Dim age As Integer = 21 If age >= 18 Then Console.WriteLine("You are eligible to vote!") Else Console.WriteLine("Sorry, you are not eligible to vote.") End If End Sub End Class $vbLabelText $csharpLabel 在上面的代碼中,我們首先聲明一個名為age的整數變量並將其賦值為21。然後,我們使用if-else語句檢查年齡是否大於或等於18。如果條件為真,程序會在控制台上打印"您有資格投票!"。 如果為假,它會打印"抱歉,您沒有資格投票。" 使用布林表達式 在C#中,您可以使用各種類型的布林表達式來創建更複雜的條件。 一些常用的條件運算符包括: ==:等於 !=:不等於 <:小於 >:大於 <=:小於或等於 >=:大於或等於 讓我們看看一個例子。 假設您想編寫一個程序來檢查一個數字是正數、負數還是零。 以下代碼片段使用if語句和條件運算符實現此功能: using System; class Program { static void Main(string[] args) { int number = 0; if (number > 0) { Console.WriteLine("The number is positive."); } else if (number < 0) { Console.WriteLine("The number is negative."); } else { Console.WriteLine("The number is zero."); } } } using System; class Program { static void Main(string[] args) { int number = 0; if (number > 0) { Console.WriteLine("The number is positive."); } else if (number < 0) { Console.WriteLine("The number is negative."); } else { Console.WriteLine("The number is zero."); } } } Imports System Friend Class Program Shared Sub Main(ByVal args() As String) Dim number As Integer = 0 If number > 0 Then Console.WriteLine("The number is positive.") ElseIf number < 0 Then Console.WriteLine("The number is negative.") Else Console.WriteLine("The number is zero.") End If End Sub End Class $vbLabelText $csharpLabel 在上面的示例中,我們首先聲明一個名為number的整數變量並將其賦值為0。然後,我們使用if語句檢查數字是否大於0。對於真值,我們打印"這個數字是正數。"對於假值,我們移動到else if語句,它檢查數字是否小於0。如果此條件為真,我們打印"這個數字是負的。" 最後,如果之前的條件均不成立,我們到達else塊,打印"這個數字是零。" 使用邏輯運算符組合條件 在某些情況下,您可能需要一次檢查多個條件。 C#提供了邏輯運算符來幫助您實現此目的。 最常用的邏輯運算符是: &&:邏輯AND ||:邏輯OR !:邏輯NOT 讓我們看看一個使用邏輯運算符與if語句的例子。 想像一下,您正在編寫一個程序來確定某人是否有資格獲得商店的特殊折扣。 該折扣適用於年滿65歲或以上的老年人或年齡在18至25歲之間的學生。 這裡是一個代碼片段,展示如何使用具有邏輯運算符的C#if-else語句來確定折扣資格: using System; class Program { static void Main(string[] args) { int age = 23; bool isStudent = true; if ((age >= 65) || (isStudent && (age >= 18 && age <= 25))) { Console.WriteLine("You are eligible for the discount!"); } else { Console.WriteLine("Sorry, you are not eligible for the discount."); } } } using System; class Program { static void Main(string[] args) { int age = 23; bool isStudent = true; if ((age >= 65) || (isStudent && (age >= 18 && age <= 25))) { Console.WriteLine("You are eligible for the discount!"); } else { Console.WriteLine("Sorry, you are not eligible for the discount."); } } } Imports System Friend Class Program Shared Sub Main(ByVal args() As String) Dim age As Integer = 23 Dim isStudent As Boolean = True If (age >= 65) OrElse (isStudent AndAlso (age >= 18 AndAlso age <= 25)) Then Console.WriteLine("You are eligible for the discount!") Else Console.WriteLine("Sorry, you are not eligible for the discount.") End If End Sub End Class $vbLabelText $csharpLabel 在以上代碼中,我們首先聲明了一個名為age的整數變量和一個名為isStudent的布林變量。 然後,我們使用if-else語句和邏輯運算符檢查該人是否有資格獲得折扣。 如果年齡65歲或以上,或如果該人是18至25歲之間的學生,則程序會打印"您有資格獲得折扣!"。否則,它會打印"抱歉,您沒有資格獲得折扣。" 使用IronPDF生成PDF:If-Else語句的相關應用 現在,您對C#if-else語句有了扎實的掌握,讓我們探索一個涉及IronPDF 庫的實用應用,它使您能夠在C#應用程序中無縫處理PDF文件。 IronPDF是一個強大的.NET庫,使您可以在C#應用程序中創建、編輯和提取PDF文件的內容。 在此示例中,我們將創建一個簡單的PDF發票生成器,根據客戶的所在地點應用不同的稅率。 這種情境提供了一個很好機會來利用if-else語句。 首先,通過運行以下命令安裝IronPDF via NuGet: Install-Package IronPdf 接下來,讓我們創建一個簡單的程序,生成具備不同地區客戶稅率的發票: using System; using IronPdf; class Program { static void Main(string[] args) { string customerLocation = "Europe"; double taxRate; // Determine tax rate based on customer location if (customerLocation == "USA") { taxRate = 0.07; } else if (customerLocation == "Europe") { taxRate = 0.20; } else { taxRate = 0.15; } double productPrice = 100.0; double totalTax = productPrice * taxRate; double totalPrice = productPrice + totalTax; string invoiceContent = $@" <h1>Invoice</h1> <p>Product Price: ${productPrice}</p> <p>Tax Rate: {taxRate * 100}%</p> <p>Total Tax: ${totalTax}</p> <p>Total Price: ${totalPrice}</p> "; // Render the HTML content to a PDF document using IronPDF var pdf = new ChromePdfRenderer(); var document = pdf.RenderHtmlAsPdf(invoiceContent); document.SaveAs("Invoice.pdf"); // Save the PDF file locally } } using System; using IronPdf; class Program { static void Main(string[] args) { string customerLocation = "Europe"; double taxRate; // Determine tax rate based on customer location if (customerLocation == "USA") { taxRate = 0.07; } else if (customerLocation == "Europe") { taxRate = 0.20; } else { taxRate = 0.15; } double productPrice = 100.0; double totalTax = productPrice * taxRate; double totalPrice = productPrice + totalTax; string invoiceContent = $@" <h1>Invoice</h1> <p>Product Price: ${productPrice}</p> <p>Tax Rate: {taxRate * 100}%</p> <p>Total Tax: ${totalTax}</p> <p>Total Price: ${totalPrice}</p> "; // Render the HTML content to a PDF document using IronPDF var pdf = new ChromePdfRenderer(); var document = pdf.RenderHtmlAsPdf(invoiceContent); document.SaveAs("Invoice.pdf"); // Save the PDF file locally } } Imports System Imports IronPdf Friend Class Program Shared Sub Main(ByVal args() As String) Dim customerLocation As String = "Europe" Dim taxRate As Double ' Determine tax rate based on customer location If customerLocation = "USA" Then taxRate = 0.07 ElseIf customerLocation = "Europe" Then taxRate = 0.20 Else taxRate = 0.15 End If Dim productPrice As Double = 100.0 Dim totalTax As Double = productPrice * taxRate Dim totalPrice As Double = productPrice + totalTax Dim invoiceContent As String = $" <h1>Invoice</h1> <p>Product Price: ${productPrice}</p> <p>Tax Rate: {taxRate * 100}%</p> <p>Total Tax: ${totalTax}</p> <p>Total Price: ${totalPrice}</p> " ' Render the HTML content to a PDF document using IronPDF Dim pdf = New ChromePdfRenderer() Dim document = pdf.RenderHtmlAsPdf(invoiceContent) document.SaveAs("Invoice.pdf") ' Save the PDF file locally End Sub End Class $vbLabelText $csharpLabel 在這段代碼中,我們使用if-else語句根據客戶的位置確定適當的稅率。 我們使用使用IronPDF從HTML字符串創建PDF發票。 在C#中,我們可以利用C#列表來存儲和操作項目,例如產品價格。 結論 在整個本教程中,我們已經涵蓋了C#if-else語句的基礎,探索了各種條件和邏輯運算符,並審視了實例來幫助更好地理解概念。 We even demonstrated a practical application using the powerful IronPDF library, which offers a free trial and licensing options. 記住,練習對掌握程式設計概念至關重要。繼續嘗試不同的情景,應用您新學到的if-else語句和其他相關概念的知識。 常見問題解答 C# 中 if 語句的目的是什么? C# 中的 if 語句用於僅在指定的布林條件為真時執行一段代碼。這對於在程式中做出決策至關重要。 if-else 語句如何增強 C# 編程? C# 中的 if-else 語句允許程序員根據條件是真還是假來執行不同的代碼塊,這對於在編程中處理各種邏輯場景至關重要。 布林表達式在 C# 的條件語句中扮演什麼角色? 布林表達式在 C# 的條件語句中至關重要,因為它們決定了控制 if 和 if-else 結構中執行流程的真值。 C# 中常用的條件運算符是哪些? C# 中常用的條件運算符包括 '==', '!=', '<', '>', '<=', '>='。這些運算符用於在 if 語句中評估條件。 如何在 C# 中使用邏輯運算符與 if 語句搭配? 邏輯運算符如 '&&'(與)、'||'(或)、'!'(非)可以在 if 語句中用於結合多個條件,從而允許評估 C# 中的複雜邏輯。 如何在 C# 中將條件邏輯應用到 PDF 生成中? 在 PDF 生成中,可以通過 if-else 語句根據特定條件應用不同的格式或內容,從而實現動態文件創建。 你可以舉一個使用 if-else 語句和邏輯運算符的例子嗎? 一個使用 if-else 語句和邏輯運算符的例子是根據年齡標準檢查是否符合折扣資格,比如符合資格的老年人或學生。 實踐 C# 中 if-else 語句的實用方法是什麼? 實踐 if-else 語句的一個實用方法是創建涉及決策邏輯的小程序,例如根據年齡判斷投票資格。 if-else 語句如何在 PDF 發票生成器中管理稅率? 在 PDF 發票生成器中,if-else 語句可用於根據地點或客戶類型等條件應用不同的稅率,從而提高發票的準確性和功能性。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# 多行字串(開發者的工作原理)安裝 NuGet Powershell(開發者...