.NET 幫助

C# If(它如何為開發者工作)

發佈 2023年5月23日
分享:

在本教程中,我們將分解 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
VB   C#

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
VB   C#

在上述情況中,如果布林表達式的結果為 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
VB   C#

在上面的代碼中,我們首先宣告一個名為 age 的整數變數,並將其賦值為 21。然後,我們使用 if else 語句來檢查年齡是否大於或等於 18。如果條件為真,程序會打印 "You are eligible to vote"。!"到控制台。如果是假的,它會打印“抱歉,您沒有資格投票。”

使用布林表達式

在 C# 中,您可以使用多種布林表達式來建立更複雜的條件。一些常用的條件運算符包括:

  • ==: 等於!```markdown
  • =: 不等
  • <: 小於
  • >: 大於
  • <=: 小於或等於
  • >=: 大於或等於

讓我們來看一個範例。假設你想寫一個程式來檢查一個數字是正數、負數還是零。以下的程式碼片段使用 if 語句和條件運算符來達到這個目的:


```cs  

    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.");
            }
         }
    }

在上面的示例中,我們首先宣告一個名為 number 的整數變數並將其賦值為 0。接著我們使用 if 語句檢查數字是否大於 0。如果條件為真,我們打印 "The number is positive." 如果條件為假,我們進入 else if 語句,檢查數字是否小於 0。如果這個條件為真,我們打印 "The number is negative." 最後,如果沒有滿足前面的任何條件,我們進入 else 區塊,打印 "The number is zero."

使用邏輯運算子結合條件

在某些情況下,您可能需要同時檢查多個條件。C# 提供了邏輯運算子來幫助您實現這一點。最常用的邏輯運算子是

  • &&:邏輯 AND
  • ||:邏輯 OR!**: 逻辑非运算符

讓我們看一個使用邏輯運算符和 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)(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
VB   C#

在上述代碼中,我們首先宣告一個名為 age 的整數變數和一個名為 isStudent 的布林變數。然後,我們使用 if else 語句結合邏輯運算符來檢查此人是否符合折扣資格。如果年齡為65歲或以上,或者此人是介於18到25歲之間的學生,程式便會輸出「您有資格享受折扣」。!否則,它會打印「抱歉,您不符合折扣資格。」

使用 IronPDF 生成 PDF 文件:if else 語句的相關應用

現在你已經對 C# 的 if else 語句有了牢固的理解,讓我們來探討一個涉及到實際應用的範例 IronPDF 圖書館。

IronPDF 是一個強大的 .NET 函式庫,允許你在 C# 應用程式中創建、編輯和提取 PDF 文件的內容。

在這個示例中,我們將創建一個簡單的 PDF 發票生成器,根據客戶的位置應用不同的稅率。這個情境提供了一個使用 if else 敘述的絕佳機會。

首先,通過運行以下指令安裝 IronPDF:

Install-Package IronPdf

接下來,讓我們創建一個簡單的程式,為不同地區的客戶生成具有不同稅率的發票:


    using System;
    using IronPdf;

    class Program
    {
        static void Main(string [] args)
        {
            string customerLocation = "Europe";
            double taxRate;

            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>
            ";

            var pdf = new ChromePdfRenderer();
            var document = pdf.RenderHtmlAsPdf(invoiceContent);
            document.SaveAs("Invoice.pdf");
        }
    }

    using System;
    using IronPdf;

    class Program
    {
        static void Main(string [] args)
        {
            string customerLocation = "Europe";
            double taxRate;

            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>
            ";

            var pdf = new ChromePdfRenderer();
            var document = pdf.RenderHtmlAsPdf(invoiceContent);
            document.SaveAs("Invoice.pdf");
        }
    }
Imports System
	Imports IronPdf

	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim customerLocation As String = "Europe"
			Dim taxRate As Double

			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>
            "

			Dim pdf = New ChromePdfRenderer()
			Dim document = pdf.RenderHtmlAsPdf(invoiceContent)
			document.SaveAs("Invoice.pdf")
		End Sub
	End Class
VB   C#

在此範例中,我們使用 if else 語句根據客戶的位置來確定適當的稅率。我們創建了 從 HTML 字串生成 PDF 發票在 C# 中,我們可以利用 C# 列表一個強大的集合類,用於存儲和操作一系列項目,如產品價格。

C# If(它如何為開發者工作)圖1

結論

在本次教程中,我們涵蓋了 C# if else 語句的基礎知識,探討了各種條件和邏輯運算符,並通過實際範例來更好地理解這個概念。我們還演示了一個實際應用使用強大的 IronPDF 庫,提供一個 免費試用 和授權證書起價為 $749。

記住,實踐對於掌握編程概念至關重要。繼續嘗試不同的場景,應用你新學到的 if else 語句和其他相關概念。

< 上一頁
C# 多行字串(開發人員如何使用)
下一個 >
安裝 NuGet Powershell(開發人員教程工作原理)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >