精通 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 lineConsole.WriteLine("Hello, C# Print Function!") ' Print a string and move to a new lineConsole.WriteLine("Hello, C# Print Function!") ' Print a string and move to a new line這一行單行程式碼將指定的字串列印到控制台,並附加一個換行字元,整齊地呈現輸出。
列印變數
列印變數值是一種常見需求。 C#通過字串插值或串聯來實現這一點。 以下是一個例子,說明變數列印:
int age = 25;
Console.WriteLine($"Age: {age}"); // Interpolating the variable 'age' into the stringint age = 25;
Console.WriteLine($"Age: {age}"); // Interpolating the variable 'age' into the stringDim age As Integer = 25
Console.WriteLine($"Age: {age}") ' Interpolating the variable 'age' into the stringDim age As Integer = 25
Console.WriteLine($"Age: {age}") ' Interpolating the variable 'age' into the string在這種情況下,age變數的值被插入到字串中,提供動態和資訊豐富的輸出。

列印使用者輸入
一個常見的場景是將使用者輸入列印到控制台。 考慮以下例子:
Console.Write("Enter your name: ");
string name = Console.ReadLine(); // Read input from the user
Console.WriteLine($"Hello, {name}!"); // Print a personalized greetingConsole.Write("Enter your name: ");
string name = Console.ReadLine(); // Read input from the user
Console.WriteLine($"Hello, {name}!"); // Print a personalized greetingConsole.Write("Enter your name: ")
Dim name As String = Console.ReadLine() ' Read input from the user
Console.WriteLine($"Hello, {name}!") ' Print a personalized greetingConsole.Write("Enter your name: ")
Dim name As String = Console.ReadLine() ' Read input from the user
Console.WriteLine($"Hello, {name}!") ' Print a personalized greeting在這種情況下,程式提示使用者輸入,捕獲它,然後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 fruitDim 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這個迴圈遍歷列表,將每個水果列印在一個單獨的行上。
列印Enum值
枚舉通常被用來表示一組命名常量。 列印枚舉值有助於視覺化和確認您程式碼中的使用情況:
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}"); // Print the current dayenum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}"); // Print the current dayFriend 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 dayFriend 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這提供了對由枚舉表示的選擇當前狀態的清晰度。

列印到控制台但不換行
如果您想在每次輸出之間不插入新行地列印文字內容,則選擇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 ClassImports 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這一系列的Write調用在同一行上生成輸出,保持一致的呈現。 這是Write方法和WriteLine方法之間的唯一差別。
使用Unicode字元列印
增強您的輸出,使用Unicode字元,為您的控制台消息增添風采。 例如:
Console.WriteLine("Hello \u2665 C#"); // \u2665 represents a heart symbolConsole.WriteLine("Hello \u2665 C#"); // \u2665 represents a heart symbolConsole.WriteLine("Hello " & ChrW(&H2665).ToString() & " C#") ' \u2665 represents a heart symbolConsole.WriteLine("Hello " & ChrW(&H2665).ToString() & " C#") ' \u2665 represents a heart symbol加入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 debugint x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}"); // Print sum to debugDim 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 debugDim 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這有助於跟踪變數值並理解計算或條件是如何被處理的。

複合格式化
複合字串格式化允許更加動態和複雜的輸出。 您可以在字串中嵌入佔位符並用值替換它們:
double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price); // Use placeholders in stringdouble price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price); // Use placeholders in stringDim price As Double = 19.99
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price) ' Use placeholders in stringDim price As Double = 19.99
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price) ' Use placeholders in string這裡,佔位符{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 formatDateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}"); // Print date in short format
Console.WriteLine($"Current Time: {currentDate:t}"); // Print time in short formatDim 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 formatDim 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定制格式化符(d、t等)允許開發者以不同的方式呈現資訊。
使用列印處理例外
當發生例外時,列印相關資訊有助於識別問題。 例如:
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 TryTry
' Some code that may throw an exception
Catch ex As Exception
Console.WriteLine($"Exception Caught: {ex.Message}") ' Print exception message
End Try列印例外資訊有助於快速診斷運行時問題。
使用IronPrint:C#列印庫的高級列印
IronPrint,由Iron Software開發,是一個強大和多功能的列印庫,旨在使.NET開發者能夠將列印功能無縫整合到他們的應用程式中。 這款全面的工具以其在多個平台上的相容性而著稱,包括Windows、macOS、Android和iOS,使其成為開發者在多樣化專案上工作的最佳解決方案。

IronPrint的一個關鍵優勢在於其對廣泛檔案格式的支持,包括PDF、PNG、HTML、TIFF、GIF、JPEG和BMP。這種靈活性使開發者能夠在他們的應用程式中處理各種列印需求。 無論您是在從事移動、桌面還是控制台應用程式開發,IronPrint都提供了一個統一的解決方案,以實現高效和可靠的列印。
IronPrint的功能集包括可自定義的列印設置,使開發者能夠根據特定需要調整列印體驗。 此外,該程式庫提供了顯示列印對話框的選項,增強了使用者互動和控制。 與不同.NET版本和專案型別的相容性進一步增強了其多功能性,使其適合於各種開發場景。
安裝
要開始使用IronPrint,請使用NuGet安裝該套件:
基本用法
使用IronPrint很簡單。 以下程式碼列印使用IronPrint來列印一個文件:
using IronPrint;
Printer.Print("document.pdf"); // Print a document using IronPrintusing IronPrint;
Printer.Print("document.pdf"); // Print a document using IronPrintImports IronPrint
Printer.Print("document.pdf") ' Print a document using IronPrintImports IronPrint
Printer.Print("document.pdf") ' Print a document using IronPrint此簡化的設置展示了IronPrint如何輕鬆地整合到您的專案中。
列印對話框
IronPrint通過允許您在列印之前顯示列印對話框來擴展功能性:
Printer.ShowPrintDialog("document.pdf"); // Show a dialog before printingPrinter.ShowPrintDialog("document.pdf"); // Show a dialog before printingPrinter.ShowPrintDialog("document.pdf") ' Show a dialog before printingPrinter.ShowPrintDialog("document.pdf") ' Show a dialog before printing此功能為使用者提供了對列印過程的額外控制。
自定義列印設置
IronPrint使您能夠根據需要自定義列印設置。 以下範例說明了如調整DPI、列印份數和紙張方向等設置的自定義:
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("document.pdf", printSettings); // Customized print settingsPrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("document.pdf", printSettings); // Customized print settingsDim printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
Printer.Print("document.pdf", printSettings) ' Customized print settingsDim printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
Printer.Print("document.pdf", printSettings) ' Customized print settings這種靈活性使您能夠根據具體需求對列印過程進行微調。 有關IronPrint及其功能的詳細資訊,請存取此文件頁面。
跨平台支持
IronPrint以其在不同環境中的相容性為傲,包括Windows、macOS、Android和iOS。 它與.NET 8、7、6、5、Core 3.1+和.NET Framework(4.6.2+)無縫整合。 無論您是為網頁、移動、桌面還是控制台開發,IronPrint都能滿足您的需求。
結論
掌握在C#中列印的藝術是建立健壯且使用者友好的應用程式的關鍵。 無論您是使用內建的Console類功能,還是利用像IronPrint這樣的高級程式庫,了解這些列印技術都至關重要。 這篇全面的文章已經讓您掌握了在不同場景中有效列印的知識,確保您的應用能無縫地與使用者和利益相關者溝通。
Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。