跳至頁尾內容
.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!");
    }
}
$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);
    }
}
$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}");
    }
}
$vbLabelText   $csharpLabel

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

其他格式選項

線路終止器

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

Console.Out.NewLine = "\n";
// Set to newline character only
Console.Out.NewLine = "\n";
// 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);
    }
}
$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));
    }
}
$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.");
    }
}
$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);
    }
}
$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("The value is " + variable);將列印一個字串,該字串由變數的值連接而成。

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

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

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

在 C# 中,可以使用轉義序列(例如\n表示換行符, \t表示製表符)在傳遞給Console.WriteLine字串中列印特殊字元。

IronPrint是什麼?它能為.NET開發人員帶來哪些好處?

IronPrint 是一個功能全面的列印庫,專為 .NET 開發人員設計,旨在簡化實體文件的列印流程。它支援跨平台環境和多種檔案格式,從而增強了易用性和跨 .NET 版本的兼容性。

如何在專案中安裝IronPrint?

IronPrint 可以使用 NuGet 套件管理器進行安裝,因此可以輕鬆地將其整合到您的 .NET 專案中,以增強列印功能。

IronPrint 支援哪些列印環境?

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

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

IronPrint 允許透過PrintSettings類別自訂列印設置,例如 DPI、份數和紙張方向,從而對列印過程進行靈活控制。

IronPrint有試用版嗎?

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

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

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。