跳至頁尾內容
.NET幫助

如何有效地使用 C# 列印行

在C#中列印行是主控台應用程式的一個基本方面,它涉及將文字或指定的值顯示在主控台螢幕上。 無論您是在使用標準輸出流還是格式化字串,了解如何有效列印行都是在C#主控台應用程式中至關重要的。

在本文中,我們將探討與在C#中列印行相關的各種方法和技術。

行基本列印

在C#中,列印行通常涉及使用Console.WriteLine方法。 讓我們從簡單的範例開始:

using System;

class Program 
{
    public static void Main() 
    {
        Console.WriteLine("Hello, C# Print Line!");
    }
}
using System;

class Program 
{
    public static void Main() 
    {
        Console.WriteLine("Hello, C# Print Line!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		Console.WriteLine("Hello, C# Print Line!")
	End Sub
End Class
$vbLabelText   $csharpLabel

在上述程式碼中,Console.WriteLine語句輸出指定的字串值("Hello, C# Print Line!"),後面跟著一個新行。這是透過WriteLine方法實現的,它在輸出結尾附加一個行終止符。

行終止符

行終止符是一個特殊字元或序列,用於表示行的結尾。兩個最常見的行終止符是回車符('\r')和換行符('\n')。 在C#中,Console.WriteLine方法負責根據操作系統來使用適當的當前行終止符。

public static void Main() 
{
    Console.WriteLine("This is on the first line.");
    Console.WriteLine("This is on the second line.");
}
public static void Main() 
{
    Console.WriteLine("This is on the first line.");
    Console.WriteLine("This is on the second line.");
}
Public Shared Sub Main()
	Console.WriteLine("This is on the first line.")
	Console.WriteLine("This is on the second line.")
End Sub
$vbLabelText   $csharpLabel

在上面的例子中,在程式執行之後,每個Console.WriteLine會在C#主控台視窗中產生一個新行,從而生成兩行指定行。

C#列印行(開發者的操作原理):圖1 - 前面程式碼的主控台輸出

指定行終止符

如果您需要顯式控制行終止符,可以使用Console.Write方法並手動增加所需的行終止符:

public static void Main() 
{
    Console.Write("This is on the first line.");
    Console.Write('\r'); // Carriage return
    Console.Write("This is on the same line but very far left position.");
}
public static void Main() 
{
    Console.Write("This is on the first line.");
    Console.Write('\r'); // Carriage return
    Console.Write("This is on the same line but very far left position.");
}
Imports Microsoft.VisualBasic

Public Shared Sub Main()
	Console.Write("This is on the first line.")
	Console.Write(ControlChars.Cr) ' Carriage return
	Console.Write("This is on the same line but very far left position.")
End Sub
$vbLabelText   $csharpLabel

在這個例子中,回車符('\r')被用來將游標位置到行的開頭,結果是文字的第二部分出現在最左側位置,也就是覆蓋之前的輸出。

C#列印行(開發者的操作原理):圖2 - 顯示\r的主控台輸出

列印多行

若要列印多行而不重複Console.WriteLine語句,您可以使用變數長度的參數列表:

public static void Main() 
{
    PrintLines("Line 1", "Line 2", "Line 3");
}

static void PrintLines(params string[] lines) 
{
    foreach (var line in lines) 
    {
        Console.WriteLine(line);
    }
}
public static void Main() 
{
    PrintLines("Line 1", "Line 2", "Line 3");
}

static void PrintLines(params string[] lines) 
{
    foreach (var line in lines) 
    {
        Console.WriteLine(line);
    }
}
Public Shared Sub Main()
	PrintLines("Line 1", "Line 2", "Line 3")
End Sub

Shared Sub PrintLines(ParamArray ByVal lines() As String)
	For Each line In lines
		Console.WriteLine(line)
	Next line
End Sub
$vbLabelText   $csharpLabel

我們建立的PrintLines方法接受指定的字串參數陣列,允許您傳遞任意數量的新行來列印指定的字串值。

C#列印行(開發者的操作原理):圖3 - 使用PrintLines方法的主控台輸出

格式化輸出

格式化輸出是至關重要的,尤其是在處理不同資料型別時。Console.WriteLine方法提供了多種重載,接受指定的物件和格式資訊:

public static void Main() 
{
    int answer = 42;
    string name = "John Doe";
    Console.WriteLine("The answer is {0}.", answer);
    Console.WriteLine("Hello, {0}!", name);
}
public static void Main() 
{
    int answer = 42;
    string name = "John Doe";
    Console.WriteLine("The answer is {0}.", answer);
    Console.WriteLine("Hello, {0}!", name);
}
Public Shared Sub Main()
	Dim answer As Integer = 42
	Dim name As String = "John Doe"
	Console.WriteLine("The answer is {0}.", answer)
	Console.WriteLine("Hello, {0}!", name)
End Sub
$vbLabelText   $csharpLabel

在這個例子中,{0}是指定物件的佔位符(在此例子中為answername),允許您在輸出中包括可變資料並列印指定的格式資訊。

C#列印行(開發者的操作原理):圖4 - 顯示格式化的主控台輸出

換行符和Unicode字元

對於特殊的換行或Unicode字元,您可以使用轉義序列。 您還可以使用Console.WriteLine列印任何ASCII字面量或有效的HTML程式碼。例如,在同一字串中包含一個單行換行:

public static void Main() 
{
    Console.WriteLine("This is line 1.\nThis is line 2.");
    Console.WriteLine("Line 1\u000Aline 2");
}
public static void Main() 
{
    Console.WriteLine("This is line 1.\nThis is line 2.");
    Console.WriteLine("Line 1\u000Aline 2");
}
Imports Microsoft.VisualBasic

Public Shared Sub Main()
	Console.WriteLine("This is line 1." & vbLf & "This is line 2.")
	Console.WriteLine("Line 1" & vbLf & "line 2")
End Sub
$vbLabelText   $csharpLabel

這裡,\n\u000A,指定的Unicode字元,均表示換行符,使文字在每種情況下移動到下一行。

C#列印行(開發者的操作原理):圖5 - 顯示換行字元的主控台輸出

隨機布林值

下面的程式碼使用Console.WriteLine方法中的字串插值。 字串插值是C# 6.0中引入的一個功能,簡化了在字串字面量中嵌入表達式或變數的過程,並正確地顯示在Console應用程式上簡化指定的布林值。

using System;

class Program
{
    static void Main()
    {
        Random rnd = new Random();
        for (int i = 1; i <= 5; i++)
        { 
            bool isTrue = rnd.Next(0, 2) == 1;
            Console.WriteLine($"True or False: {isTrue}");
        }
    }
}
using System;

class Program
{
    static void Main()
    {
        Random rnd = new Random();
        for (int i = 1; i <= 5; i++)
        { 
            bool isTrue = rnd.Next(0, 2) == 1;
            Console.WriteLine($"True or False: {isTrue}");
        }
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		Dim rnd As New Random()
		For i As Integer = 1 To 5
			Dim isTrue As Boolean = rnd.Next(0, 2) = 1
			Console.WriteLine($"True or False: {isTrue}")
		Next i
	End Sub
End Class
$vbLabelText   $csharpLabel

從表達式中返回的指定資料按如下所示列印在主控台應用程式上:

C#列印行(開發者的操作原理):圖6 - 使用字串插值顯示布林值的主控台輸出

列印不同數值格式

列印各種數值格式是程式設計中常見的需求,特別是在處理雙精度浮點和單精度浮點數時。 同樣,Console.WriteLine語句可以用來精確和輕鬆地列印它們。

雙精度浮點數

double doubleValue = 0.123456789;
Console.WriteLine($"Double Precision: {doubleValue:F7}");
double doubleValue = 0.123456789;
Console.WriteLine($"Double Precision: {doubleValue:F7}");
Dim doubleValue As Double = 0.123456789
Console.WriteLine($"Double Precision: {doubleValue:F7}")
$vbLabelText   $csharpLabel

在這個例子中,F7指定雙值應以小數點後7位數字格式化。 您可以調整'F'後的數字來控制精度。

現有字串

string existingString = "Hello, C#!";
Console.WriteLine($"Existing String: {existingString}");
string existingString = "Hello, C#!";
Console.WriteLine($"Existing String: {existingString}");
Dim existingString As String = "Hello, C#!"
Console.WriteLine($"Existing String: {existingString}")
$vbLabelText   $csharpLabel

列印現有字串很簡單。 只需使用Console.WriteLine並包含您想顯示的字串。

單精度浮點數

float singleValue = 0.123456789f;
Console.WriteLine($"Single Precision: {singleValue:F7}");
float singleValue = 0.123456789f;
Console.WriteLine($"Single Precision: {singleValue:F7}");
Dim singleValue As Single = 0.123456789F
Console.WriteLine($"Single Precision: {singleValue:F7}")
$vbLabelText   $csharpLabel

與雙精度類似,F7格式規範亦適用於單精度浮點數。 您可以根據您的精度要求調整'F'後的數字。

Unlocking Powerful Printing Capabilities with IronPrint in C

列印文件是許多應用程式的基本方面,而在C#中充分利用列印潛力時,IronPrint作為一個多功能且功能豐富的程式庫而脫穎而出。

IronPrint簡介

IronPrint由Iron Software開發,是為.NET生態系統設計的高級列印程式庫,包括C#。 無論您是在開發桌面應用程式、移動應用程式還是網頁應用程式,IronPrint都可以無縫整合到您的C#專案中,提供一組廣泛的工具來處理各種列印需求。

C#列印行(開發者的操作原理):圖7 - IronPrint網頁

IronPrint的關鍵功能

1. 跨平台相容性:

IronPrint支持包括Windows、macOS、Android和iOS在內的各種操作系統。 這種跨平台的相容性確保您的列印解決方案可以覆蓋到不同環境中的使用者。

2. .NET版本支援:

與.NET Framework 4.6.2及以上版本、.NET Core 3.1+和最新的.NET版本相容,IronPrint涵蓋了廣泛的.NET環境。

3. 專案型別支援:

IronPrint迎合不同的專案型別,包括移動(Xamarin和MAUI)、桌面(WPF和MAUI)和主控台(應用程式和程式庫)。 這種靈活性使其適合多種應用程式架構。

4. 簡易安裝:

使用IronPrint很簡單。 您可以通過NuGet Package Manager Console快速安裝此程式庫並執行Install-Package IronPrint命令。

IronPrint的基本用法

這是一個簡單的範例,演示如何在C#主控台應用程式中輕鬆使用IronPrint來列印文件:

using IronPrint;

class Program
{
    static void Main()
    {
        Console.WriteLine("Printing Started...");
        // Silent printing of a document
        Printer.Print("document.pdf");
        // Or display a print dialog
        Printer.ShowPrintDialog("document.pdf");
        Console.WriteLine("Printing Completed...");
    }
}
using IronPrint;

class Program
{
    static void Main()
    {
        Console.WriteLine("Printing Started...");
        // Silent printing of a document
        Printer.Print("document.pdf");
        // Or display a print dialog
        Printer.ShowPrintDialog("document.pdf");
        Console.WriteLine("Printing Completed...");
    }
}
Imports IronPrint

Friend Class Program
	Shared Sub Main()
		Console.WriteLine("Printing Started...")
		' Silent printing of a document
		Printer.Print("document.pdf")
		' Or display a print dialog
		Printer.ShowPrintDialog("document.pdf")
		Console.WriteLine("Printing Completed...")
	End Sub
End Class
$vbLabelText   $csharpLabel

這裡的輸出顯示了使用PrintShowPrintDialog方法列印文件。 如果未安裝實體印表機,則使用預設印表機進行列印。

C#列印行(開發者的操作原理):圖8 - 列印開始彈出視窗和儲存列印輸出彈出視窗

進階列印功能

IronPrint超越了基本的列印任務,並提供了以下進階功能:

  • 靜默列印:使用Printer.PrintAsync列印文件而不顯示對話框。
  • 自定列印設定:使用PrintSettings類調整列印參數。
  • 異步列印:異步執行列印操作以防止阻塞主執行緒。
  • 選擇印表機:GetPrinterNames方法允許您從可用的印表機中選擇,提供更細緻的列印過程控制。

平台特定調整

IronPrint允許您針對不同平台定制您的列印解決方案。 例如,在處理針對特定平台如Windows、Android、iOS或macOS的.NET Core專案時,您可以根據情況調整專案文件中的TargetFrameworks屬性。

要獲取有關IronPrint的更多詳細資訊,請存取此文件API參考頁面。

結論

在C#中列印行是一項開發主控台應用程式的基本技能。 無論您是顯示文字、格式化輸出還是控制行終止符,了解可用的各種技術將提高您建立高效和可讀的主控台程式的能力。 探索由Console類提供的多樣化方法,試驗格式選項,充分利用C#的靈活性以在應用程式中產生清晰且結構良好的主控台輸出。

IronPrint 是對C#開發者尋求強大而靈活的列印功能的重要盟友。 憑藉其跨平台支援、與多個.NET版本的相容性和進階列印功能,IronPrint簡化了在多樣化的C#應用程式中實現列印方案的過程。 無論您是在為桌面、移動還是網頁開發,IronPrint為您提供所需的工具,使您的列印需求在C#開發世界中成為現實。

IronPrint為商業用途提供免費試用。 從此處下載程式庫並試用。

常見問題

如何在C#控制台應用程式中列印文字?

要在C#控制台應用程式中列印文字,您可以使用Console.WriteLine方法,該方法輸出指定的字串值並加上新行。若要獲得更大的控制力,請使用Console.Write手動管理行結束符號。

在C#中控制行結束符號的方法有哪些?

在C#中,您可以使用Console.Write方法並附加字元如'\n'以表示新行或'\r'以表示回車符來控制行結束符號。

如何在C#中一次列印多行?

您可以通過建立一個接受可變長度參數列表的方法並迭代每一行以使用Console.WriteLine進行列印來一次列印多行。

一個多功能的C#列印程式庫應該具備哪些功能?

一個多功能的C#列印程式庫應該支持跨平台功能、各種.NET版本和多樣化的專案型別。像IronPrint這樣的功能,例如無聲列印、自定列印設定、非同步列印和印表機選擇是必不可少的。

如何在C#控制台應用程式中格式化輸出?

您可以在C#控制台應用程式中使用Console.WriteLine,使用像{0}這樣的佔位符來格式化輸出,以允許動態內容的顯示。

我能否在C#控制台輸出中使用特殊行中斷和Unicode?

是的,您可以使用如'\n'這樣的轉義序列進行行中斷,並在控制台輸入中使用像'\u000A'這樣的Unicode字元。

如何在C#中以精確方式列印數值?

要在C#中以精確方式列印數值,請在Console.WriteLine中使用格式規範符,例如'F2'是用於定義小數位數的浮點數。

C#列印程式庫的進階功能是什麼?

C#列印程式庫的進階功能包括無聲列印、自定列印設定、非同步列印和印表機選擇,可通過像Printer.PrintAsyncGetPrinterNames這樣的方法實現於IronPrint中。

如何在我的C#專案中安裝全面的列印程式庫?

您可以使用NuGet套件管理器主控台中的命令Install-Package IronPrint將類似IronPrint的列印程式庫安裝到您的C#專案中。

全面的C#列印程式庫是否提供免費試用版?

是的,IronPrint可提供免費試用版,這是一個全面的C#列印程式庫,可從Iron Software網站下載,用於商業用途。

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天。
聊天
電子郵件
給我打電話