在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
在這個綜合教程中,我們將涵蓋在public static void Main
方法中開始使用for迴圈所需了解的一切。 我們將探索 for 迴圈、迴圈變數、迴圈主體、迭代變數、內外層迴圈、無限迴圈、布林表達式、巢狀迴圈等。 讓我們開始吧!
for
迴圈是在 C# 中的一種迴圈,專為您確切知道需要迭代多少次的情況而設計。 C# 中 for
迴圈的語法如下代碼塊所示:
for (initialization; condition; increment)
{
// Loop body
}
for (initialization; condition; increment)
{
// Loop body
}
initialization
Do While condition
' Loop body
increment
Loop
讓我們分解 for 迴圈的組成部分:
初始化:這是宣告和初始化迴圈變數或迭代變數的地方。
條件:一個布林/條件表達式,決定循環是否應繼續多次執行語句。
在 C# 中,static void Main
方法或 static void Main(String []args)
是應用程式的入口點。 這是您的程式開始執行的地方。 以下是一個在static void Main
方法中使用for迴圈的範例:
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("This is the first for loop!");
}
}
}
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("This is the first for loop!");
}
}
}
Imports System
Friend Class Program
Shared Sub Main()
For i As Integer = 0 To 4
Console.WriteLine("This is the first for loop!")
Next i
End Sub
End Class
在此範例中,迴圈變數int i
初始化為0,並作為該變數。 只要 i
小於 5
,迴圈將持續執行。 在每次迭代後,增量運算i++會將i的值增加1。
C# 中的巢狀迴圈 是放置在其他迴圈內的迴圈,形成一個內部迴圈和一個具有迭代器部分的外部迴圈。 當您處理像矩陣這樣的多維數據結構時,或者當您需要對每一組元素的組合執行某個操作時,這些功能可能會很有幫助。
以下是一個在 C# 中具有內部循環在外部循環中的巢狀 for 迴圈範例:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine($"i: {i}, j: {j}");
}
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine($"i: {i}, j: {j}");
}
}
For i As Integer = 0 To 2
For j As Integer = 0 To 1
Console.WriteLine($"i: {i}, j: {j}")
Next j
Next i
在此範例中,外層迴圈執行並以i
等於0開始。內層迴圈然後在進入下一個i
值之前,遍歷所有可能的j
值。
無限迴圈是一個永不結束的迴圈,因為其測試條件從未為假。 這些可能是危險的,因為它們可能導致您的程式無限期地掛起。 在編寫迴圈(如 while 迴圈或 foreach
迴圈)時要小心,以確保最終滿足退出條件。 以下是 C# 中沒有指定條件的無限迴圈範例。
// This is an example of an infinite loop
for (int i = 0; ; i++)
{
Console.WriteLine("This loop will run forever!");
}
// This is an example of an infinite loop
for (int i = 0; ; i++)
{
Console.WriteLine("This loop will run forever!");
}
' This is an example of an infinite loop
Dim i As Integer = 0
Do
Console.WriteLine("This loop will run forever!")
i += 1
Loop
除了標準的 for 迴圈結構外,C# 還提供了迴圈控制語句,例如 break
和 continue
,可以幫助您更有效地管理迴圈。
break
:此語句用於立即退出迴圈。遇到 break
語句時,迴圈會終止,程式會繼續執行迴圈外的下一行程式碼。continue
:此語句用於跳過當前迭代中迴圈主體的其餘代碼,並跳至迴圈的下一次迭代。
以下是一個展示如何在 for 迴圈中使用 break
和 continue
的範例:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exits the loop when i is equal to 5
}
if (i % 2 == 0)
{
continue; // Skips even numbers
}
Console.WriteLine($"Odd number: {i}");
}
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exits the loop when i is equal to 5
}
if (i % 2 == 0)
{
continue; // Skips even numbers
}
Console.WriteLine($"Odd number: {i}");
}
For i As Integer = 0 To 9
If i = 5 Then
Exit For ' Exits the loop when i is equal to 5
End If
If i Mod 2 = 0 Then
Continue For ' Skips even numbers
End If
Console.WriteLine($"Odd number: {i}")
Next i
在這個例子中,當i
到達5
時,迴圈停止執行。 continue
語句用於跳過偶數,所以只會列印小於 5
的奇數。
迴圈條件是一個布林值,用來決定迴圈是否應該繼續執行。 在每次迭代之前會評估此表達式,並且只有在表達式為 true
時,循環才會運行。 許多迴圈中常用的布林表達式包括:
i < 10
、i >= 10
、i >= 10
、i == 10
、i != 10
邏輯運算子:&&
(AND),**
** (或), **
!`** (非)
您可以使用邏輯運算符將多個表達式組合起來,以創建更复杂的迴圈條件。 例如:
for (int i = 0; i < 10 && i != 5; i++)
{
Console.WriteLine(i);
}
for (int i = 0; i < 10 && i != 5; i++)
{
Console.WriteLine(i);
}
Dim i As Integer = 0
Do While i < 10 AndAlso i <> 5
Console.WriteLine(i)
i += 1
Loop
在此範例中,迴圈將在i
小於10
且不等於5
時執行。
程式碼區塊是一組用大括號{}
括起來的語句。 在 for 迴圈中,緊隨迴圈聲明之後的程式碼塊稱為迴圈主體。 這是您要在每次迴圈迭代中執行的程式碼放置處。
for (int i = 0; i < 5; i++)
{
// This is the loop body
Console.WriteLine($"Iteration: {i}");
}
for (int i = 0; i < 5; i++)
{
// This is the loop body
Console.WriteLine($"Iteration: {i}");
}
For i As Integer = 0 To 4
' This is the loop body
Console.WriteLine($"Iteration: {i}")
Next i
在這個範例中,迴圈主體由單一的Console.WriteLine
語句組成,它會輸出當前的迭代次數。
當你的程式碼中遇到 for 迴圈時,會發生以下一系列事件:
迴圈變數已初始化。
布林表達式被評估。 如果表達式為false
,則跳過迴圈,程式將繼續執行迴圈外的下一行程式碼。
如果表達式是true
,則會執行迴圈主體。
迴圈變數被遞增或更新。
false
。了解 IronPDF 的 PDF 生成功能,以在 C# 中創建動態且強大的 PDF 報告。 在處理 for 迴圈時,這可能是一個有用的工具,特別是當您需要根據迴圈中處理的資料創建動態報告或文件時。 在本節中,我們將向您展示如何結合使用IronPDF和C# for迴圈來生成簡單報告。
首先,您需要安裝 IronPDF NuGet 套件。 您可以在 Visual Studio 中使用套件管理器主控台來完成此操作:
Install-Package IronPDF
安裝了IronPDF之後,讓我們創建一個簡單的範例,使用IronPDF從HTML生成一個PDF報告,其中包含一個使用for迴圈生成的數字及其平方的表格。
步驟 1:添加必要的命名空間。
using IronPdf;
using System.IO;
using IronPdf;
using System.IO;
Imports IronPdf
Imports System.IO
步驟2:創建一個名為GenerateReport
的新方法。
static void GenerateReport()
{
// Create an HTML template for the report
var htmlTemplate = @"
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
</style>
</head>
<body>
<h1>Number Squares Report</h1>
<table>
<thead>
<tr>
<th>Number</th>
<th>Square</th>
</tr>
</thead>
<tbody>
{0}
</tbody>
</table>
</body>
</html>";
// Generate the table rows using a for loop
string tableRows = "";
for (int i = 1; i <= 10; i++)
{
tableRows += $"<tr><td>{i}</td><td>{i * i}</td></tr>";
}
// Insert the generated table rows into the HTML template
string finalHtml = string.Format(htmlTemplate, tableRows);
// Create a new PDF document from the HTML using two variables
var pdf = new IronPdf.ChromePdfRenderer();
var document = pdf.RenderHtmlAsPdf(finalHtml);
// Save the PDF to a file
document.SaveAs("NumberSquaresReport.pdf");
}
static void GenerateReport()
{
// Create an HTML template for the report
var htmlTemplate = @"
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
</style>
</head>
<body>
<h1>Number Squares Report</h1>
<table>
<thead>
<tr>
<th>Number</th>
<th>Square</th>
</tr>
</thead>
<tbody>
{0}
</tbody>
</table>
</body>
</html>";
// Generate the table rows using a for loop
string tableRows = "";
for (int i = 1; i <= 10; i++)
{
tableRows += $"<tr><td>{i}</td><td>{i * i}</td></tr>";
}
// Insert the generated table rows into the HTML template
string finalHtml = string.Format(htmlTemplate, tableRows);
// Create a new PDF document from the HTML using two variables
var pdf = new IronPdf.ChromePdfRenderer();
var document = pdf.RenderHtmlAsPdf(finalHtml);
// Save the PDF to a file
document.SaveAs("NumberSquaresReport.pdf");
}
Shared Sub GenerateReport()
' Create an HTML template for the report
Dim htmlTemplate = "
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
</style>
</head>
<body>
<h1>Number Squares Report</h1>
<table>
<thead>
<tr>
<th>Number</th>
<th>Square</th>
</tr>
</thead>
<tbody>
{0}
</tbody>
</table>
</body>
</html>"
' Generate the table rows using a for loop
Dim tableRows As String = ""
For i As Integer = 1 To 10
tableRows &= $"<tr><td>{i}</td><td>{i * i}</td></tr>"
Next i
' Insert the generated table rows into the HTML template
Dim finalHtml As String = String.Format(htmlTemplate, tableRows)
' Create a new PDF document from the HTML using two variables
Dim pdf = New IronPdf.ChromePdfRenderer()
Dim document = pdf.RenderHtmlAsPdf(finalHtml)
' Save the PDF to a file
document.SaveAs("NumberSquaresReport.pdf")
End Sub
從您的Program.cs文件中呼叫GenerateReport
方法:
GenerateReport();
GenerateReport();
GenerateReport()
當您執行此示例時,將在您的應用程式輸出目錄中生成一份名為「NumberSquaresReport.pdf」的PDF報告。 報告將包含一個表格,列出從 1 到 10 的數字及其平方,這是使用 C# 的 for 迴圈生成的。
總之,這個綜合教程已為您提供了 C# 中 for 迴圈及其相關概念的堅實基礎。我們探討了迴圈變數、迴圈主體、迭代變數、內部和外部迴圈、無限迴圈、布林表達式、程式碼區塊、巢狀迴圈,甚至演示瞭如何整合強大的 IronPDF 庫,以使用 for 迴圈生成動態 PDF 報告。
IronPDF 提供免費試用版,讓您測試其功能,如果您覺得有用,授權選項從適合您需求的價格開始。