.NET 幫助

C#列印功能(它對開發者的運作方式)

發佈 2024年4月3日
分享:

在 C# 中列印是開發人員的基本技能,使他們能夠與用戶交流並記錄重要資訊。Console 類是一個多功能的工具,提供一系列方法以應對不同的情境。微軟 C# 程式語言還提供 列印方法 可以用來打印到紙張上。

在這篇全面的文章中,我們將探討C#打印的各個方面,涵蓋基本技術、變量打印、列表打印、高級功能以及深入探討IronPrint庫。

基本打印使用 Console.WriteLine

在 C# 打印的核心是 Console.WriteLine 方法。這是顯示格式化輸出資訊到控制台的首選函數。此方法的簡單性在以下範例中顯而易見:

Console.WriteLine("Hello, C# Print Function!"); // string line
Console.WriteLine("Hello, C# Print Function!"); // string line
Console.WriteLine("Hello, C# Print Function!") ' string line
VB   C#

此單行將指定的字符串行打印到控制台,隨後是換行符,整齊地呈現輸出。

列印變數

列印變數值是一個常見需求。C# 通過字串插值或串接來實現這一點。以下是一個說明變數列印的範例:

int age = 25;
Console.WriteLine($"Age: {age}");
int age = 25;
Console.WriteLine($"Age: {age}");
Dim age As Integer = 25
Console.WriteLine($"Age: {age}")
VB   C#

在此情況下,age 變數的值被插入到字串中,提供了一個動態且有資訊的輸出。

C#列印功能(開發人員如何使用):圖1 - 同行變數輸出

打印用戶輸入

一個常見的情況是將用戶輸入打印到控制臺。考慮以下示例:

Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
Console.Write("Enter your name: ")
Dim name As String = Console.ReadLine()
Console.WriteLine($"Hello, {name}!")
VB   C#

在這種情況下,程式會提示使用者輸入,捕捉輸入後,WriteLine 方法會打印出個性化的問候訊息。

列印清單

清單在 C# 程式語言中非常普遍,列印其元素是一項實用的技能。以下程式碼示範了如何在新的一行上列印清單的每個元素:

List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit);
}
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit);
}
Dim fruits As New List(Of String) From {"Apple", "Banana", "Orange"}
For Each fruit In fruits
	Console.WriteLine(fruit)
Next fruit
VB   C#

這個循環迭代列表,並將每個水果分別列印在不同的行上。

列印列舉值

列舉通常用來表示一組命名常數。列印列舉值有助於在您的程式碼中可視化並確認它們的使用:

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}");
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}");
Friend Enum Days
	Sunday
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
End Enum
Private today As Days = Days.Wednesday
Console.WriteLine($"Today is {today}")
VB   C#

這提供了對由枚舉表示的當前選擇狀態的清晰說明。

C# 列印功能(對開發人員的運作方式):圖 2 - Enum 輸出

打印到控制台而不換行

如果您想在每次輸出之間不引入新行地打印文本內容,Console.Write 方法是您的選擇。此方法可以防止輸出移至下一行。

using System;
class Program
{
    public static void Main(object [] sender) // object sender
    {
        Console.Write("This ");
        Console.Write("will ");
        Console.Write("be ");
        Console.Write("on ");
        Console.Write("the ");
        Console.Write("same ");
        Console.Write("line. Even it contains more lines");
    }
}
using System;
class Program
{
    public static void Main(object [] sender) // object sender
    {
        Console.Write("This ");
        Console.Write("will ");
        Console.Write("be ");
        Console.Write("on ");
        Console.Write("the ");
        Console.Write("same ");
        Console.Write("line. Even it contains more lines");
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main(ByVal sender() As Object) ' object sender
		Console.Write("This ")
		Console.Write("will ")
		Console.Write("be ")
		Console.Write("on ")
		Console.Write("the ")
		Console.Write("same ")
		Console.Write("line. Even it contains more lines")
	End Sub
End Class
VB   C#

這一系列的 Write 調用在同一行上產生輸出,保持連貫的呈現方式。這是 Write 方法和 WriteLine 方法之間的唯一區別。

使用 Unicode 字元列印

透過 Unicode 字元增強您的輸出,為您的控制臺訊息增添風采。例如:

Console.WriteLine("Hello \u2665 C#");
// \u2665 represents a heart symbol
Console.WriteLine("Hello \u2665 C#");
// \u2665 represents a heart symbol
Console.WriteLine("Hello " & ChrW(&H2665).ToString() & " C#")
' \u2665 represents a heart symbol
VB   C#

包含 Unicode 字元可以使您的控制台輸出更加美觀。

使用打印語句偵錯

在開發過程中,打印語句對於偵錯非常有價值。通過在代碼中有策略地放置Console.WriteLine語句,您可以輸出變數值或執行點,以理解程式流程並識別問題。

int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}");
int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}");
Dim x As Integer = 5
Dim y As Integer = 10
Dim sum As Integer = x + y
Console.WriteLine($"The sum of {x} and {y} is {sum}")
VB   C#

這有助於追踪變數的值並了解計算或條件是如何被處理的。

C# 打印功能(對開發人員的作用):圖 3 - 調試輸出

複合格式化

複合字串格式化允許更動態和複雜的輸出。您可以在字串中嵌入佔位符並用值替換它們:

double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price);
double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price);
Dim price As Double = 19.99
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price)
VB   C#

這裡,佔位符 {0}{1} 替換為相應的值,提供了一種靈活的方式來構建您的輸出。

格式化日期和時間

打印當前日期和時間是一個常見的需求。C# 提供了各種格式化選項來顯示日期和時間信息:

DateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}");
Console.WriteLine($"Current Time: {currentDate:t}");
DateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}");
Console.WriteLine($"Current Time: {currentDate:t}");
Dim currentDate As DateTime = DateTime.Now
Console.WriteLine($"Current Date: {currentDate:d}")
Console.WriteLine($"Current Time: {currentDate:t}")
VB   C#

自訂格式指定字元 (dt 等。) 允許開發人員以不同的方式呈現信息。

使用 Print 處理異常

當異常發生時,打印相關信息可以幫助識別問題。例如:

try {
      // Some code that may throw an exception
} catch (Exception ex) {
      Console.WriteLine($"Exception Caught: {ex.Message}");
}
try {
      // Some code that may throw an exception
} catch (Exception ex) {
      Console.WriteLine($"Exception Caught: {ex.Message}");
}
Try
	  ' Some code that may throw an exception
Catch ex As Exception
	  Console.WriteLine($"Exception Caught: {ex.Message}")
End Try
VB   C#

打印例外訊息有助於在執行期間快速診斷問題。

先進打印 IronPrint:C# 打印庫

IronPrint由 Iron Software 開發, 是一個強大且多功能的列印庫,旨在讓 .NET 開發人員可以無縫整合列印功能到他們的應用程式中。這個綜合工具因其在各種平台(包括Windows、macOS、Android和iOS)上的兼容性而脫穎而出,成為開發人員在處理各種專案時的首選解決方案。

C# 列印功能(開發人員如何使用):圖4 - IronPrint

IronPrint 的一個主要優勢在於其廣泛的文件格式支持,包含 PDF、PNG、HTML、TIFF、GIF、JPEG 和 BMP。這種靈活性允許開發者在他們的應用程式中處理各種列印需求。無論您是處理行動設備、桌面或控制台應用程式,IronPrint 都提供了一個統一的解決方案,以實現高效且可靠的列印。

IronPrint 的功能集合包括可自訂的列印設定,使開發者能夠根據特定需求來調整列印體驗。此外,該庫還提供顯示列印對話框的選項,增強使用者互動和控制。與不同 .NET 版本和專案類型的兼容性進一步增強了其多功能性,適用於各種開發情境。

安裝

要開始使用 IronPrint,請透過 NuGet 安裝套件:

Install-Package IronPrint

基本用法

使用IronPrint很簡單。以下的代碼 列印 使用 IronPrint 的文件:

using IronPrint;
Printer.Print("document.pdf");
using IronPrint;
Printer.Print("document.pdf");
Imports IronPrint
Printer.Print("document.pdf")
VB   C#

此最低限度的設置展示了 IronPrint 是如何輕鬆整合到您的專案中。

打印對話框

IronPrint 擴展了功能,允許您顯示 列印對話框 列印前:

Printer.ShowPrintDialog("document.pdf");
Printer.ShowPrintDialog("document.pdf");
Printer.ShowPrintDialog("document.pdf")
VB   C#

此功能讓使用者在列印過程中有更多的控制權。

自訂列印設定

IronPrint 讓您能夠自訂 列印設定 根據您的要求。以下範例說明如何自訂設定,例如DPI、副本數量和紙張方向:

PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait; Printer.Print("document.pdf", printSettings);
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait; Printer.Print("document.pdf", printSettings);
Dim printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
Printer.Print("document.pdf", printSettings)
VB   C#

這種靈活性讓您能夠根據特定需求微調打印過程。欲了解有關 IronPrint 及其功能的更多信息,請訪問此 文檔 頁面。

跨平台支援

IronPrint 具有與各種環境相容的特點,包括 Windows、macOS、Android 和 iOS。它可以無縫整合到 .NET 8、7、6、5、Core 3.1+ 以及 .NET Framework。 (4.6.2+)無論您是在為網頁、行動裝置、桌面還是主機開發,IronPrint 都能滿足您的需求。

結論

掌握在 C# 中打印的技巧對於創建健壯且用戶友好的應用程式至關重要。無論是使用 Console 類的內建功能,還是利用像 IronPrint 這樣的高級庫,了解這些打印技術都是至關重要的。這篇綜合文章已經提供了在各種情境中有效打印的知識,確保您的應用程式能夠與用戶和利害關係人無縫溝通。

IronPrint 雖然是一個付費庫, 免費試用 並且其 Lite 套件從 $749 開始。從 下載該庫 這裡.

< 上一頁
C# 印出變數(對開發者的運作方式)
下一個 >
C# 列印清單(適用於開發人員的工作方式)

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

免費 NuGet 下載 總下載次數: 9,531 查看許可證 >