跳過到頁腳內容
.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# 中,您可以使用各種類型的布林表達式來建立更複雜的條件。 一些常用的條件運算符號包括

  • ===:平等
  • !=: 不等式
  • <: Less than
  • ``:大於
  • <=: Less than or equal to
  • =:大於或等於

讓我們來看看一個範例。 假設您要寫一個程式來檢查一個數字是正數、負數或零。 下面的程式碼片段使用 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。如果此條件為真,我們會列印 "The number is negative"。最後,如果前面的條件都不符合,我們到達 else 區塊,列印 "The number is zero"。

使用邏輯運算符組合條件

在某些情況下,您可能需要同時檢查多個條件。 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 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 語句來使用邏輯運算符號?

邏輯運算符號如 '&&' (AND)、'||「 (OR) 及 」!' (NOT) 可在 if 語句中使用,以結合多個條件,允許在 C# 中評估複雜的邏輯。

如何使用 C# 在 PDF 生成中應用條件邏輯?

使用 if-else 語句的條件邏輯可以用在 PDF 產生中,根據特定條件套用不同的格式或內容,實現動態文件的建立。

您能舉例說明如何使用 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 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

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

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。