跳過到頁腳內容
.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

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

Advanced Printing with IronPrint: The C# Print Library

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核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我