跳至頁尾內容
.NET幫助

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

在C#中列印是開發者的一項基礎技能,使他們能與使用者溝通並記錄重要資訊。 Console類是個多功能的工具,提供了一系列的方法以滿足不同場景的需求。 Microsoft C#程式語言還提供了一個Print method,可用於列印到紙上。

在這篇綜合文章中,我們將探索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
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
Dim age As Integer = 25
Console.WriteLine($"Age: {age}") ' Interpolating the variable 'age' into the string
$vbLabelText   $csharpLabel

在這種情況下,age變數的值被插入到字串中,提供動態和資訊豐富的輸出。

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
Console.Write("Enter your name: ")
Dim name As String = 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
}
Dim fruits As New List(Of String) From {"Apple", "Banana", "Orange"}
For Each fruit In fruits
	Console.WriteLine(fruit) ' Print each element on a new line
Next fruit
$vbLabelText   $csharpLabel

這個迴圈遍歷列表,將每個水果列印在一個單獨的行上。

列印Enum值

枚舉通常被用來表示一組命名常量。 列印枚舉值有助於視覺化和確認您程式碼中的使用情況:

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
Friend Enum Days
	Sunday
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
End Enum
Private today As Days = Days.Wednesday
Console.WriteLine($"Today is {today}") ' Print the current day
$vbLabelText   $csharpLabel

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

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

列印到控制台但不換行

如果您想在每次輸出之間不插入新行地列印文字內容,則選擇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.");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main(ByVal args() As String)
		' 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.")
	End Sub
End Class
$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
Console.WriteLine("Hello " & ChrW(&H2665).ToString() & " 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
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}") ' 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
Dim price As Double = 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
Dim currentDate As DateTime = 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
}
Try
	' Some code that may throw an exception
Catch ex As Exception
	Console.WriteLine($"Exception Caught: {ex.Message}") ' Print exception message
End Try
$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安裝該套件:

Install-Package IronPrint

基本用法

使用IronPrint很簡單。 以下程式碼列印使用IronPrint來列印一個文件:

using IronPrint;

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

Printer.Print("document.pdf"); // Print a document using IronPrint
Imports 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
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
Dim printSettings As 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+)無縫整合。 無論您是為網頁、移動、桌面還是控制台開發,IronPrint都能滿足您的需求。

結論

掌握在C#中列印的藝術是建立健壯且使用者友好的應用程式的關鍵。 無論您是使用內建的Console類功能,還是利用像IronPrint這樣的高級程式庫,了解這些列印技術都至關重要。 這篇全面的文章已經讓您掌握了在不同場景中有效列印的知識,確保您的應用能無縫地與使用者和利益相關者溝通。

儘管IronPrint是一個付費的程式庫,但免費試用和它的Lite套件從$999開始。 從這裡下載該程式庫。

常見問題

如何在 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 字元?

您可以通過在字串中嵌入 Unicode 跳脫序列,如 \u2665 代表心形符號,來列印 Unicode 字元。

C# 中 Console.WriteLine 的常見用途是什麼?

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

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

IronPrint 可以通過安裝程式庫並使用其方法來管理列印設定、處理列印對話方塊,以及跨不同平台支持多種文件格式來整合到 C# 專案中。

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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