跳過到頁腳內容
.NET幫助

C# If(開發者的工作原理)

在本教程中,我們將分解 ifelse 語句的概念,以及如何在 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

if 語句檢查給定的布林表達式是否計算為 true。 如果有,則會執行語句區塊內的程式碼 (大括號內的程式碼)。 如果布林表達式的計算結果為 false,則跳過語句區塊內的程式碼。

If-Else 語句的力量

現在,如果您想要在 if 條件為 false 時執行其他程式碼,該怎麼辦? 這就是可選的 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# 提供邏輯運算符號可協助您達成此目標。 最常用的邏輯運算符號有

  • &&:邏輯與
  • ||:邏輯或
  • !:邏輯非

讓我們來看看使用邏輯運算符與 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 for .NET 是一個功能強大的 .NET 函式庫,可讓您在 C# 應用程式中建立、編輯 PDF 檔案,並從 PDF 檔案中擷取內容。

在本範例中,我們將建立一個簡單的 PDF 發票產生器,可根據客戶所在地應用不同的稅率。 此情境提供了使用 if-else 語句的絕佳機會。

首先,透過 NuGet 執行下列指令安裝 IronPDF:

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# List 來儲存和操作項目,例如產品價格。

C# If (How It Works For Developers) 圖 1

結論

在本教程中,我們涵蓋了 C# if-else 語句的基本原理、探討了各種條件和邏輯運算符號,並檢視了真實示例,以便更好地理解這個概念。 我們甚至使用功能強大的 IronPDF 函式庫來示範實際應用,該函式庫提供免費試用和授權選項

請記住,在掌握程式設計概念時,練習是至關重要的。不斷嘗試不同的情境,應用您新發現的 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 語句可用於根據地點或客戶類型等條件應用不同的稅率,從而提高發票的準確性和功能性。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我