跳過到頁腳內容
.NET幫助

C# 打印語句:學習基礎

列印是應用程式開發的一個基本方面,它允許開發人員透過控制台或實體文件與使用者進行溝通。 在 C# 中, print 語句是用來顯示資訊的通用工具,在本文中,我們將探討它的用法、選項和最佳實務。

C# 列印語句簡介

在 C# 中, print語句用於將資訊輸出到控制台。 它促進了程式與使用者之間的溝通,提供了一種顯示訊息、資料或操作結果的方式。 該語句對於調試、使用者互動以及程式執行期間的一般資訊輸出至關重要。

基本語法

C# 中print語句的基本語法涉及使用Console.WriteLine方法,該方法會自動在指定的字串或值後面新增一行。 Console 類別位於 System 命名空間中,它包含 WriteLine 方法,用於將資訊輸出到標準輸出流。 此方法既可以處理包含多個變數的字串行,也可以處理透過標準輸入流取得的使用者輸入。

下面是一個簡單的例子:

using System;

class Program
{
    public static void Main()
    {
        // Print a greeting message to the console
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Print a greeting message to the console
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Print a greeting message to the console
		Console.WriteLine("Hello, C# Print Statement!")
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個簡單的範例中, Console類別的WriteLine方法用於將指定的字串列印到控制台,並在後面新增一行。

列印變數和值

你可以透過將字串字面量和變數的數值作為參數包含在Console.WriteLine方法中來列印它們。 舉例來說

using System;

class Program
{
    public static void Main()
    {
        // Define a string message and an integer number
        string message = "Welcome to C#";
        int number = 42;

        // Print the message and number to the console
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Define a string message and an integer number
        string message = "Welcome to C#";
        int number = 42;

        // Print the message and number to the console
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Define a string message and an integer number
		Dim message As String = "Welcome to C#"
		Dim number As Integer = 42

		' Print the message and number to the console
		Console.WriteLine(message)
		Console.WriteLine("The answer is: " & number)
	End Sub
End Class
$vbLabelText   $csharpLabel

上面的程式碼範例展示如何使用WriteLine方法將messagenumber變數的值列印到控制台。

C# 列印語句(開發者如何理解):圖 1 - Console.WriteLine 輸出

特殊字元和字串格式化

C# 提供了多種使用佔位符或字串插值來格式化輸出的方法。 請查看以下範例:

using System;

class Program
{
    public static void Main()
    {
        // Initialize variables
        string name = "John";
        int age = 30;

        // Use placeholders for string formatting
        Console.WriteLine("Name: {0}, Age: {1}", name, age);

        // Use string interpolation for a cleaner approach
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Initialize variables
        string name = "John";
        int age = 30;

        // Use placeholders for string formatting
        Console.WriteLine("Name: {0}, Age: {1}", name, age);

        // Use string interpolation for a cleaner approach
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Initialize variables
		Dim name As String = "John"
		Dim age As Integer = 30

		' Use placeholders for string formatting
		Console.WriteLine("Name: {0}, Age: {1}", name, age)

		' Use string interpolation for a cleaner approach
		Console.WriteLine($"Name: {name}, Age: {age}")
	End Sub
End Class
$vbLabelText   $csharpLabel

兩種方法都能達到相同的效果,即允許將變數值插入格式化字串中。

其他格式選項

線路終止器

預設情況下,行終止符為"\r\n"(回車符 + 換行符)。 您可以使用以下方法更改它:

Console.Out.NewLine = "\n";
// Set to newline character only
Console.Out.NewLine = "\n";
// Set to newline character only
Imports Microsoft.VisualBasic

Console.Out.NewLine = vbLf
' Set to newline character only
$vbLabelText   $csharpLabel

自訂格式

格式字串允許使用佔位符和格式選項進行自訂。 舉例來說

using System;

class Program
{
    public static void Main()
    {
        // Get the current date
        DateTime currentDate = DateTime.Now;

        // Print the current date in a long date pattern
        Console.WriteLine("Today is {0:D}", currentDate);
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Get the current date
        DateTime currentDate = DateTime.Now;

        // Print the current date in a long date pattern
        Console.WriteLine("Today is {0:D}", currentDate);
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Get the current date
		Dim currentDate As DateTime = DateTime.Now

		' Print the current date in a long date pattern
		Console.WriteLine("Today is {0:D}", currentDate)
	End Sub
End Class
$vbLabelText   $csharpLabel

複合格式

以下是一個複合格式化並將字元陣列印在一行上的範例:

using System;

class Program
{
    public static void Main()
    {
        // Define a price and character array
        double price = 19.99;
        char[] chars = { 'A', 'B', 'C' };

        // Format the output string using placeholders
        Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", 
                          "Widget", price, new string(chars));
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Define a price and character array
        double price = 19.99;
        char[] chars = { 'A', 'B', 'C' };

        // Format the output string using placeholders
        Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", 
                          "Widget", price, new string(chars));
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Define a price and character array
		Dim price As Double = 19.99
		Dim chars() As Char = { "A"c, "B"c, "C"c }

		' Format the output string using placeholders
		Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", "Widget", price, New String(chars))
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個程式碼範例中,產品名稱和價格使用複合格式進行格式化,字元使用new string(chars)作為字串列印。

新行和換行符

控制新行和換行對於建立輸出至關重要。 Console.WriteLine方法會自動新增一行,但您可以使用Console.Write方法在同一行列印,如下例所示:

using System;

class Program
{
    public static void Main()
    {
        // Print parts of a sentence on the same line
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Print parts of a sentence on the same line
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Print parts of a sentence on the same line
		Console.Write("This ")
		Console.Write("is ")
		Console.Write("on ")
		Console.WriteLine("the same line.")
	End Sub
End Class
$vbLabelText   $csharpLabel

上面的程式碼範例會產生如下列印輸出:"這是同一行。 "

IronPrint:您的 .NET 一體化列印庫

IronPrint由 Iron Software 開發,是一個全面的列印庫,專為 .NET 開發人員設計,用於列印實體文件。 它提供了廣泛的功能並支援各種環境,使其成為 C# 應用程式中列印文件的多功能解決方案。 如果實體印表機不可用,則使用預設印表機作為預設值來列印文件。

C# 列印語句(開發人員的工作原理):圖 2 - IronPrint for .NET:C# 列印庫

安裝

IronPrint可以透過NuGet程式包管理器控制台或 Visual Studio 套件管理器進行安裝。

若要使用 NuGet 套件管理器控制台安裝 IronPrint,請使用下列命令:

Install-Package IronPrint

或者,您可以使用 Visual Studio 將其安裝到您的專案中。 右鍵單擊"解決方案資源管理器",然後按一下"管理解決方案的 NuGet 套件管理器"。 在 NuGet 瀏覽標籤中,搜尋IronPrint ,然後按一下"安裝"將其新增至您的專案:

! C# 列印語句(開發人員的工作方式):圖 3 - 使用 NuGet 套件管理員安裝 IronPrint,方法是在 NuGet 套件管理員的搜尋列中搜尋"ironprint",然後選擇專案並點擊"安裝"按鈕。

為什麼選擇 IronPrint?

1. 跨平台魔法

無論您使用的是 Windows、macOS、iOS 還是 Android 系統, IronPrint都能為您提供支援。 它與 .NET 版本 8、7、6、5 和 Core 3.1+ 相容性良好,使其用途非常廣泛。

2. 格式彈性

從 PDF 到 PNG、HTML、TIFF、GIF、JPEG、IMAGE 和 BITMAP – IronPrint 都能處理。

3. 列印設定

允許自訂列印設置,包括 DPI、份數、紙張方向等。

4. 安裝簡便

安裝 IronPrint 非常簡單。只需使用 NuGet 套件管理器控制台並輸入命令: Install-Package IronPrint ,即可完成安裝。

它是如何運作的?

使用 IronPrint 進行印刷簡直易如反掌。 請看這個簡單的程式碼範例,您可以輕鬆地透過dialog進行列印並控制列印設定

using IronPrint;

class PrintExample
{
    public static void Main()
    {
        // Print a document
        Printer.Print("newDoc.pdf");

        // Show a print dialog for user interaction
        Printer.ShowPrintDialog("newDoc.pdf");

        // Customize print settings
        PrintSettings printSettings = new PrintSettings
        {
            Dpi = 150,
            NumberOfCopies = 2,
            PaperOrientation = PaperOrientation.Portrait
        };

        // Print using the customized settings
        Printer.Print("newDoc.pdf", printSettings);
    }
}
using IronPrint;

class PrintExample
{
    public static void Main()
    {
        // Print a document
        Printer.Print("newDoc.pdf");

        // Show a print dialog for user interaction
        Printer.ShowPrintDialog("newDoc.pdf");

        // Customize print settings
        PrintSettings printSettings = new PrintSettings
        {
            Dpi = 150,
            NumberOfCopies = 2,
            PaperOrientation = PaperOrientation.Portrait
        };

        // Print using the customized settings
        Printer.Print("newDoc.pdf", printSettings);
    }
}
Imports IronPrint

Friend Class PrintExample
	Public Shared Sub Main()
		' Print a document
		Printer.Print("newDoc.pdf")

		' Show a print dialog for user interaction
		Printer.ShowPrintDialog("newDoc.pdf")

		' Customize print settings
		Dim printSettings As New PrintSettings With {
			.Dpi = 150,
			.NumberOfCopies = 2,
			.PaperOrientation = PaperOrientation.Portrait
		}

		' Print using the customized settings
		Printer.Print("newDoc.pdf", printSettings)
	End Sub
End Class
$vbLabelText   $csharpLabel

有關IronPrint及其作為列印中心的功能的更多詳細信息,請訪問文件頁面

結論

C# 中的print語句是一個強大的工具,可用於與使用者溝通、顯示資訊和偵錯程式碼。 無論你是新手還是經驗豐富的開發者,了解如何有效地使用Console.WriteLine方法對於創建資訊豐富且用戶友好的應用程式都至關重要。

如果您想要精準、易用且快速的列印庫, IronPrint是您的理想之選。 無論您是在建立 Web 應用程式、使用 MAUI、Avalonia 或任何與 .NET 相關的項目, IronPrint都能為您提供支援。

IronPrint是一個付費圖書館,但提供免費試用

想讓你的開發者生活更輕鬆一點嗎? 從這裡獲取IronPrint

常見問題解答

C# 中 print 語句的目的是什麼?

在 C# 中,打印語句主要使用 Console.WriteLine 來在控制台顯示資訊。它在除錯、使用者互動,以及向使用者呈現資料或訊息時扮演關鍵的角色。

如何在 C# 中使用 Console.WriteLine 列印字串和變數?

您可以使用 Console.WriteLine 來列印字串和變數,只要將它們傳送為參數即可。例如,Console.WriteLine(「值是 」 + 變數); 將列印與變數值連接的字串。

C# 中的輸出格式化有哪些選項?

C# 提供了多種格式化選項,包括使用 $"「 語法進行字串插值,以及使用占位符進行複合格式化,例如 Console.WriteLine(」The total is {0}", total);

如何使用 Console.WriteLine 列印特殊字符?

特殊字符可以使用 C# 中的轉義序列印出,例如在傳給 Console.WriteLine 的字串中,以 \n 表示換行,或以 \t 表示制表符。

什麼是 IronPrint,它如何讓 .NET 開發人員獲益?

IronPrint 是專為 .NET 開發人員設計的全面性列印函式庫,可方便列印實體文件。它支援跨平台環境和各種檔案格式,增強了易用性和跨 .NET 版本的相容性。

如何在專案中安裝使用 IronPrint?

IronPrint 可使用 NuGet Package Manager 進行安裝,因此可直接整合到您的 .NET 專案中,以增強列印功能。

IronPrint 支援哪些列印環境?

IronPrint 支援多種環境,包括 Windows、macOS、iOS 和 Android,並與 .NET 版本 8、7、6、5 和 Core 3.1+ 相容。

如何在 .NET 應用程式中使用 IronPrint 自訂列印設定?

IronPrint 允許透過 PrintSettings 類自訂 DPI、份數和紙張方向等列印設定,提供彈性的列印流程控制。

IronPrint 是否有試用版?

是的,IronPrint 提供免費試用版,開發人員可以試用以評估其功能以及在專案中的整合能力。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

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

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。