在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
在本教程中,我們將剖析if
和else
語句的概念,以及如何在您的 C# 程式中有效地使用它們。 我們還將探索相關概念,例如布林表達式和條件運算符。 那麼,我們直接開始吧!
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
if語句檢查給定的布林表達式是否評估為true
。 如果確實如此,語句區塊內的代碼(用大括號括起的代碼)將被執行。 如果布林表達式評估為false
,則語句塊中的代碼將被跳過。
現在,若您想在 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
在上述情況下,如果布林表達式的值為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
在上述代碼中,我們首先宣告一個名為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
在上述範例中,我們首先宣告一個名為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
在上述代碼中,我們首先宣告一個名為age
的整數變量和一個名為isStudent
的布林變量。 接著,我們使用帶有邏輯運算符的 if-else 語句來檢查這個人是否符合折扣資格。 如果年齡是65歲或以上,或者如果該人是年齡介於18到25歲之間的學生,則程式會印出「您有資格獲得折扣!」否則,它會印出「抱歉,您沒有資格獲得折扣。」
既然您已經對 C# if-else 語句有了扎實的掌握,讓我們來探索一個涉及 IronPDF library 的實際應用,它允許您在 C# 應用中無縫地處理 PDF 文件。
IronPDF 是一個強大的 .NET 程式庫,允許您在 C# 應用程式中創建、編輯和提取 PDF 文件中的內容。
在此範例中,我們將建立一個簡單的 PDF 發票生成器,根據客戶所在位置套用不同的稅率。 這個情境提供了一個絕佳的機會來使用 if-else 語句。
首先,通過運行以下命令通過 NuGet 安裝 IronPDF:
Install-Package 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
在此代碼範例中,我們使用 if-else 語句來根據顧客的位置確定適當的稅率。 我們使用IronPDF從HTML字串創建PDF發票。 在 C# 中,我們可以利用 C# List 儲存和操作項目,例如產品價格。
在本教程中,我們介紹了C#的if-else語句的基礎知識,探索了各種條件和邏輯運算符,並通過實際例子來更好地理解這一概念。 我們甚至展示了一個實際應用,使用強大的IronPDF庫,該庫提供免費試用和授權選項。
請記住,練習對掌握程式設計概念至關重要。持續嘗試不同的情境,應用你新學到的if-else語句及其他相關概念。