跳至頁尾內容
.NET 幫助

精通 C# 列印函數:開發者指南

C# 中的列印是開發人員的基礎技能,使他們能夠與使用者溝通並記錄關鍵訊息。 Console類別是一個功能強大的工具,它提供了一系列方法來應對不同的場景。 Microsoft C# 程式語言也提供了一個Print 方法,可用於列印到紙張上。

在這篇全面的文章中,我們將探討 C# 列印的各個方面,涵蓋基本技術、變數列印、清單列印、進階功能以及對 IronPrint 庫的深入探索。

使用 Console.WriteLine 進行基本列印

C# 列印功能的核心是Console.WriteLine方法。 它是用於在控制台上顯示格式化輸出資訊的首選函數。 這種方法的簡潔性在以下範例中顯而易見:

Console.WriteLine("Hello, C# Print Function!"); // Print a string and move to a new line
Console.WriteLine("Hello, C# Print Function!"); // Print a string and move to a new line
$vbLabelText   $csharpLabel

這一行程式碼會將指定的字串列印到控制台,並在後面加上一個換行符,從而整齊地呈現輸出結果。

列印變數

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

int age = 25;
Console.WriteLine($"Age: {age}"); // Interpolating the variable 'age' into the string
int age = 25;
Console.WriteLine($"Age: {age}"); // Interpolating the variable 'age' into the string
$vbLabelText   $csharpLabel

在這種情況下,年齡變數的值會插入字串中,從而提供動態且資訊豐富的輸出。

C# 列印函數(開發者使用方法):圖 1 - 同一行變數輸出

列印使用者輸入

常見的應用場景是將使用者輸入列印到控制台。 請考慮以下範例:

Console.Write("Enter your name: ");
string name = Console.ReadLine(); // Read input from the user
Console.WriteLine($"Hello, {name}!"); // Print a personalized greeting
Console.Write("Enter your name: ");
string name = Console.ReadLine(); // Read input from the user
Console.WriteLine($"Hello, {name}!"); // Print a personalized greeting
$vbLabelText   $csharpLabel

在這種情況下,程式會提示使用者輸入,擷取輸入內容,然後 WriteLine 方法會列印個人化的問候語。

列印清單

清單在 C# 程式語言中很常見,列印清單元素是一項有用的技能。 以下程式碼示範如何將清單中的每個元素列印在新的一行上:

List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit); // Print each element on a new line
}
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit); // Print each element on a new line
}
$vbLabelText   $csharpLabel

此循環遍歷列表,並將每種水果列印在單獨的一行上。

列印枚舉值

枚舉通常用於表示一組命名的常數。 列印枚舉值有助於視覺化和確認它們在程式碼中的用法:

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}"); // Print the current day
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}"); // Print the current day
$vbLabelText   $csharpLabel

這有助於明確枚舉所表示的目前選擇狀態。

C# 列印函數(開發者使用方法):圖 2 - 枚舉輸出

列印到控制台時不換行符

如果您想列印文字內容而不在每行之間換行,可以使用Console.Write方法。此方法可防止輸出換行。

using System;

class Program
{
    public static void Main(string[] args) 
    {
        // Each Write call adds text to the current line
        Console.Write("This ");
        Console.Write("will ");
        Console.Write("be ");
        Console.Write("on ");
        Console.Write("the ");
        Console.Write("same ");
        Console.Write("line.");
    }
}
using System;

class Program
{
    public static void Main(string[] args) 
    {
        // Each Write call adds text to the current line
        Console.Write("This ");
        Console.Write("will ");
        Console.Write("be ");
        Console.Write("on ");
        Console.Write("the ");
        Console.Write("same ");
        Console.Write("line.");
    }
}
$vbLabelText   $csharpLabel

這一系列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
$vbLabelText   $csharpLabel

在控制台輸出中加入 Unicode 字符,可以使其更具視覺吸引力。

使用列印語句進行調試

在開發過程中,列印語句對於除錯至關重要。 透過在程式碼中策略性地放置Console.WriteLine語句,您可以輸出變數值或執行點,從而了解程式流程並識別問題。

int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}"); // Print sum to debug
int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}"); // Print sum to debug
$vbLabelText   $csharpLabel

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

C# 列印函數(開發者使用方法):圖 3 - 偵錯輸出

複合格式化

複合字串格式化允許輸出更動態、更複雜的內容。 您可以在字串中嵌入佔位符,並將其替換為值:

double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price); // Use placeholders in string
double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price); // Use placeholders in string
$vbLabelText   $csharpLabel

這裡,佔位符{0}{1}被對應的值替換,從而提供了一種靈活的方式來組織輸出。

格式化日期和時間

列印當前日期和時間是一項常見需求。 C# 提供了多種格式化選項來顯示日期和時間資訊:

DateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}"); // Print date in short format
Console.WriteLine($"Current Time: {currentDate:t}"); // Print time in short format
DateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}"); // Print date in short format
Console.WriteLine($"Current Time: {currentDate:t}"); // Print time in short format
$vbLabelText   $csharpLabel

自訂格式說明符( dt等)可讓開發人員以不同的方式呈現資訊。

使用列印處理異常

當出現異常情況時,列印相關資訊有助於識別問題所在。 舉例來說

try 
{
    // Some code that may throw an exception
} 
catch (Exception ex) 
{
    Console.WriteLine($"Exception Caught: {ex.Message}"); // Print exception message
}
try 
{
    // Some code that may throw an exception
} 
catch (Exception ex) 
{
    Console.WriteLine($"Exception Caught: {ex.Message}"); // Print exception message
}
$vbLabelText   $csharpLabel

列印異常訊息有助於在運行時快速診斷問題。

使用 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 安裝軟體包:

nuget install IronPrint
nuget install IronPrint
SHELL

基本用法

使用 IronPrint 非常簡單。 以下程式碼使用 IronPrint列印文件:

using IronPrint;

Printer.Print("document.pdf"); // Print a document using IronPrint
using IronPrint;

Printer.Print("document.pdf"); // Print a document using IronPrint
$vbLabelText   $csharpLabel

這種極簡的設定方式展現了 IronPrint 如何輕鬆地整合到您的專案中。

帶對話框的列印

IronPrint 擴展了功能,讓您在列印前顯示列印對話方塊

Printer.ShowPrintDialog("document.pdf"); // Show a dialog before printing
Printer.ShowPrintDialog("document.pdf"); // Show a dialog before printing
$vbLabelText   $csharpLabel

此功能使用戶能夠對列印過程進行更多控制。

自訂列印設定

IronPrint 使您能夠根據自己的需求自訂列印設定。 以下範例說明如何自訂 DPI、份數和紙張方向等設定:

PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("document.pdf", printSettings); // Customized print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("document.pdf", printSettings); // Customized print settings
$vbLabelText   $csharpLabel

這種靈活性使您能夠根據具體需求微調列印過程。 有關 IronPrint 及其功能的更多信息,請訪問此文件頁面。

跨平台支援

IronPrint 擁有與多種環境的兼容性,包括 Windows、macOS、Android 和 iOS。 它與 .NET 8、7、6、5、Core 3.1+ 和 .NET Framework (4.6.2+) 無縫整合。 無論您是為 Web、行動裝置、桌上型裝置或遊戲主機開發應用,IronPrint 都能滿足您的需求。

結論

掌握 C# 中的列印技巧對於創建強大且用戶友好的應用程式至關重要。 無論您是使用Console類別的內建功能,還是利用 IronPrint 等高級庫,了解這些列印技術都至關重要。 本文內容全面,使您掌握了在各種場景下有效列印的知識,確保您的應用程式能夠與使用者和利害關係人無縫溝通。

IronPrint 是一個付費庫,提供免費試用,其 Lite 套餐起價為$799 。 從這裡下載庫檔案。

常見問題解答

如何增強 C# 應用程式的列印功能?

為了增強 C# 應用程式的列印功能,您可以使用 IronPrint 庫。它支援多種檔案格式,提供可自訂的列印設置,並且相容於 Windows、macOS、Android 和 iOS 等平台。

C# 中在控制台上顯示輸出的主要方法是什麼?

在 C# 中,將輸出顯示在控制台上的主要方法是Console.WriteLine 。它用於在控制台應用程式中顯示格式化的文字和值。

如何在C#中列印清單中的元素?

要在 C# 中列印列表元素,可以使用foreach循環遍歷列表,並使用Console.WriteLine輸出每個元素。

C# 中的複合格式是什麼?

C# 中的複合格式化允許你在字串中使用佔位符,這些佔位符會被替換為指定的值。例如, Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price)使用佔位符來組織輸出。

如何在C#中格式化日期和時間?

C# 提供了格式說明符,例如「d」表示短日期,「t」表示短時間。您可以將這些說明符與DateTime.Now結合使用,以列印格式化的日期和時間。

如何在C#中列印Unicode字元?

在 C# 中,可以透過在字串中嵌入 Unicode 轉義序列(例如心形符號的\u2665來列印 Unicode 字元。

在 C# 中, Console.WriteLine有哪些常見用法?

在 C# 中, Console.WriteLine通常用於在控制台應用程式中列印變數值、偵錯、記錄資訊以及與使用者通訊。

如何將 IronPrint 整合到 C# 專案中?

透過安裝程式庫並使用其方法來管理列印設定、處理列印對話方塊以及支援不同平台上的各種檔案格式,可以將 IronPrint 整合到 C# 專案中。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。