IRONSOFTWAREHOME
.NET幫助

C# 列印變數:簡化您的程式碼

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年4月21日

在C#中列印變數是每位開發者應具備的基本技能。 無論您是在除錯程式碼、向使用者顯示資訊,還是僅僅檢查程式的狀態,Console.WriteLine語句都是進行標準輸出流操作時的首選工具。 來自命名空間SystemConsole類別提供了WriteWriteLine方法,用於將變數值列印到控制台視窗。

在這篇全面的文章中,我們將探討C#中列印變數的各個方面,涵蓋不同的資料型別、格式選項和進階技術。

基本變數列印

我們可以使用Console.WriteLine方法輕鬆列印數值,如下方的程式碼範例所示。

int integerValue = 42; // Declare and initialize an integer variable
Console.WriteLine($"Integer Value: {integerValue}"); // Print the integer value using string interpolation

在這個基礎範例中,我們宣告一個整數變數(integerValue)並使用Console.WriteLine語句將指定的值列印到控制台。 字串前的**$**符號允許我們使用字串插值法將變數直接嵌入字串常量中。

字串變數列印

string greeting = "Hello, C#!"; // Declare and initialize a string variable
Console.WriteLine($"Greeting: {greeting}"); // Print the string value using string interpolation

列印字串變數遵循相同的模式。 我們宣告一個字串變數(greeting),賦予一個字串值("Hello, C#!"),並使用Console.WriteLine進行輸出。 這對於顯示訊息或任何文字資訊非常有用。

C# 列印變數(開發者使用方法):圖1 - 字串變數輸出

如果您想在同一行上列印變數值,您可以使用Console.Write方法。 這兩個方法的唯一區別是WriteLine在結尾會留下一個新行字元,因此下一次輸出會被列印在下一行,而Write會將所有內容列印在同一行。

單行多變數

int x = 5, y = 10; // Declare and initialize multiple integers
Console.WriteLine($"X: {x}, Y: {y}"); // Print multiple variables using string interpolation

您可以在單行內通過用逗號將它們分隔來列印多個變數。 這對於一起顯示相關資訊的情況非常有利。

C# 列印變數(開發者使用方法):圖2 - 單行多變數輸出

變數格式化

double piValue = Math.PI; // Assign the mathematical constant Pi
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}"); // Format to 5 decimal places and print

格式化至關重要,特別是對於浮點數來說。 在此,F5格式規範確保了Pi值會以小數點後五位數的形式列印。

變數串連

int apples = 3, oranges = 5; // Declare and initialize integer variables for fruit counts
Console.WriteLine("Total Fruits: " + (apples + oranges)); // Calculate the total and print using concatenation

字串串連可以用於更複雜的輸出。 在這裡,水果的總數量被計算出來並在單行內列印。

列印變數型別

bool isTrue = true; // Declare and initialize a boolean variable
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}"); // Print the value and type of the variable

有時,顯示的不僅是變數的預設值,還包括變數的型別。 **GetType()**方法實現了這一點。

列印變數的進階技術

Using String.Format

int width = 10, height = 5; // Declare dimensions
string formattedOutput = String.Format("Dimensions: {0} x {1}", width, height); // Format the string
Console.WriteLine(formattedOutput); // Print formatted output

String.Format方法提供了一種格式化字串和列印變數的另一種方法,提供了對輸出結構的更多控制。

逐字字串常量

string filePath = @"C:\MyDocuments\file.txt"; // Use verbatim to handle file paths
Console.WriteLine($"File Path: {filePath}"); // Print the file path

對於帶有轉義字元的路徑或字串,逐字字串常量(以**@**為前綴)可以簡化程式碼。 在此,字串格式化幫助我們輕鬆地列印文件路徑。

控制台輸出控制

重定向控制台輸出

以下程式碼範例可幫助您將控制台視窗輸出寫入文件:

using System;
using System.IO;

class Program
{
    public static void Main(string[] args)
    {
        string outputPath = "output.txt"; // Specify the output file path
        using (StreamWriter sw = new StreamWriter(outputPath))
        {
            Console.SetOut(sw); // Redirect console output to a file
            Console.WriteLine("This will be written to the file."); // This output goes to the file
        }
    }
}

將控制台輸出重定向到文件可以讓您捕獲並保存輸出以供進一步分析或記錄。

控制台顏色

Console.ForegroundColor = ConsoleColor.Red; // Set text color to red
Console.WriteLine("This text will be displayed in red."); // Print in specified color
Console.ResetColor(); // Reset color to default

更改控制台文字顏色為特定輸出增加了視覺上的強調,使分辨資訊的不同型別更加容易。

IronPrint: 為 .NET 開發者賦予進階列印功能

IronPrint是由Iron Software開發的一個強大的列印程式庫。 IronPrint 是一個綜合性的列印程式庫,旨在無縫整合於.NET應用程式中。 IronPrint 作為可靠且功能豐富的 .NET 開發者列印程式庫而存在。 其跨平台相容性、對各種文件格式的支持以及可自訂設置使其成為處理多樣列印任務的寶貴工具。 無論您是為桌面、移動或網頁應用程式開發,IronPrint 提供了一個多用途解決方案,以滿足您在不斷發展的.NET 開發領域中的列印需求。

C# 列印變數(開發者使用方法):圖3 - IronPrint

它提供了一系列功能,使開發者能夠處理從基本文件列印到可自訂設置和跨平台相容的多樣列印需求。

主要特點

  1. **格式支持:**IronPrint 支持多種文件格式,包括PDF、PNG、HTML、TIFF、GIF、JPEG和BITMAP。這種靈活性確保開發人員能夠處理不同型別的列印內容。
  2. **可自訂設置:**開發者可以根據應用程式的需求自由自訂列印設置。 這包括設置DPI(每英寸點數)、指定紙張方向(縱向或橫向)和控制副本數量的選項。
  3. **列印對話框:**IronPrint 通過允許開發者在列印前顯示列印對話框來促進無縫的使用者體驗。 這在需要使用者與列印過程互動並選擇特定選項的情況下非常有用。

相容性與安裝

IronPrint 擁有跨不同 .NET 版本的廣泛相容性,使其可供廣泛的開發人員使用。 它支持.NET 8、7、6、5和Core 3.1+,以及.NET Framework(4.6.2+)。 該程式庫適用於各類專案型別,包括移動(Xamarin,MAUI)、桌面(WPF,MAUI,Windows Avalonia)和控制台應用程式。

安裝

要開始使用IronPrint,開發者可以快速使用NuGet包管理器安裝該程式庫。

PM > Install-Package IronPrint

或者,可以直接從官方IronPrint NuGet網站下載此包或使用NuGet包管理器進行解決方案。

應用授權金鑰

在使用IronPrint功能之前,開發者需要應用有效的授權或試用金鑰。 這涉及將授權金鑰分配給License類別的LicenseKey屬性。 以下程式碼片段演示了此步驟:

using IronPrint; 

// Apply license key
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";

程式碼範例

列印文件

要使用IronPrint 列印文件,開發者只需將文件路徑傳遞給Print方法:

using IronPrint;

// Print the document
Printer.Print("newDoc.pdf");

帶對話框列印

在需要列印對話框的情況下,可以使用ShowPrintDialog方法:

using IronPrint;

// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");

自訂列印設置

要以程式方式配置列印設置,開發者可以實例化PrintSettings類別:

using IronPrint;

// Configure print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;

// Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings);

有關更多程式碼範例,請存取此程式碼範例頁面。

結論

在C#中列印變數是每位開發者應該掌握的基本技能。 Console.WriteLine語句結合各種格式化技術,如字串串連、字串常量和字串插值,提供了一種靈活且有效的方式來輸出變數值。 當您探索更複雜的情境,例如使用不同的資料型別和進階的格式化選項時,您將增強在C#程式中有效傳達資訊的能力。

IronPrint 是一個需要付費的程式庫,但開發者可以使用免費試用授權來探索其功能。 有關更多資訊,開發者可以存取官方文件API參考頁面。 從這裡下載該程式庫並試用。

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

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

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預約您的免費
現場演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲得非義務性諮詢
完成下列表單或發郵件到sales@ironsoftware.com
您的資訊將始終保密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立