.NET幫助 C# 打印變量:簡化您的代碼 Jacob Mellor 更新:6月 22, 2025 下載 IronPrint NuGet 下載 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在雙子座打開 請向 Gemini 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 在 C# 中列印變數是任何開發人員都必須掌握的技能。 無論你是偵錯程式碼、向使用者顯示訊息,還是只是檢查程式的狀態, Console.WriteLine語句都是你進行標準輸出流操作的首選工具。 System命名空間中的Console類別提供了Write和WriteLine方法,用於將變數值列印到控制台視窗。 在這篇全面的文章中,我們將探討C# 中列印變數的各個方面,涵蓋不同的資料類型、格式化選項和進階技巧。 基礎變數列印 我們可以使用 Console.WriteLine 方法輕鬆列印數值,如下面的程式碼範例所示。 int integerValue = 42; // Declare and initialize an integer variable Console.WriteLine($"Integer Value: {integerValue}"); // Print the integer value using string interpolation int integerValue = 42; // Declare and initialize an integer variable Console.WriteLine($"Integer Value: {integerValue}"); // Print the integer value using string interpolation Dim integerValue As Integer = 42 ' Declare and initialize an integer variable Console.WriteLine($"Integer Value: {integerValue}") ' Print the integer value using string interpolation $vbLabelText $csharpLabel 在這個基本範例中,我們宣告一個整數變數( integerValue ),並使用Console.WriteLine語句將指定的值列印到控制台。 字串前的$符號允許我們使用字串插值將變數直接嵌入到字串字面量中。 字串變數列印 string greeting = "Hello, C#!"; // Declare and initialize a string variable Console.WriteLine($"Greeting: {greeting}"); // Print the string value using string interpolation string greeting = "Hello, C#!"; // Declare and initialize a string variable Console.WriteLine($"Greeting: {greeting}"); // Print the string value using string interpolation Dim greeting As String = "Hello, C#!" ' Declare and initialize a string variable Console.WriteLine($"Greeting: {greeting}") ' Print the string value using string interpolation $vbLabelText $csharpLabel 列印字串變數也遵循同樣的模式。 我們宣告一個字串變數( 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 int x = 5, y = 10; // Declare and initialize multiple integers Console.WriteLine($"X: {x}, Y: {y}"); // Print multiple variables using string interpolation Dim x As Integer = 5, y As Integer = 10 ' Declare and initialize multiple integers Console.WriteLine($"X: {x}, Y: {y}") ' Print multiple variables using string interpolation $vbLabelText $csharpLabel 您可以透過在字串中用逗號分隔多個變量,在一行中列印多個變數。 這樣有利於將相關資訊一起展示。 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 double piValue = Math.PI; // Assign the mathematical constant Pi Console.WriteLine($"Approximate Value of Pi: {piValue:F5}"); // Format to 5 decimal places and print Dim piValue As Double = Math.PI ' Assign the mathematical constant Pi Console.WriteLine($"Approximate Value of Pi: {piValue:F5}") ' Format to 5 decimal places and print $vbLabelText $csharpLabel 格式設定至關重要,尤其是對於浮點數而言。 在這裡, 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 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 Dim apples As Integer = 3, oranges As Integer = 5 ' Declare and initialize integer variables for fruit counts Console.WriteLine("Total Fruits: " & (apples + oranges)) ' Calculate the total and print using concatenation $vbLabelText $csharpLabel 字串連接可用於產生更複雜的輸出。 這裡,水果的總數會被計算出來,並印在一行中。 列印變數類型 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 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 Dim isTrue As Boolean = True ' Declare and initialize a boolean variable Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}") ' Print the value and type of the variable $vbLabelText $csharpLabel 有時,不僅顯示變數的預設值,還要顯示變數的類型,這樣會更有益。 GetType()方法可以實現這一點。 變數列印的高級技術 使用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 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 Dim width As Integer = 10, height As Integer = 5 ' Declare dimensions Dim formattedOutput As String = String.Format("Dimensions: {0} x {1}", width, height) ' Format the string Console.WriteLine(formattedOutput) ' Print formatted output $vbLabelText $csharpLabel String.Format方法提供了另一種格式化字串和列印變數的方法,可以更好地控制輸出結構。 逐字字串字面量 string filePath = @"C:\MyDocuments\file.txt"; // Use verbatim to handle file paths Console.WriteLine($"File Path: {filePath}"); // Print the file path string filePath = @"C:\MyDocuments\file.txt"; // Use verbatim to handle file paths Console.WriteLine($"File Path: {filePath}"); // Print the file path Dim filePath As String = "C:\MyDocuments\file.txt" ' Use verbatim to handle file paths Console.WriteLine($"File Path: {filePath}") ' Print the file path $vbLabelText $csharpLabel 對於包含轉義字元的路徑或字串,可以使用逐字字串字面量(以@為前綴)來簡化程式碼。 在這裡,字串格式化有助於輕鬆列印檔案路徑。 控制台輸出控制 重定向控制台輸出 以下程式碼範例可協助您將控制台視窗的輸出寫入檔案: 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 } } } 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 } } } Imports System Imports System.IO Friend Class Program Public Shared Sub Main(ByVal args() As String) Dim outputPath As String = "output.txt" ' Specify the output file path Using sw As 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 End Using End Sub End Class $vbLabelText $csharpLabel 將控制台輸出重定向到文件,可以捕獲並保存輸出,以便進行進一步分析或記錄日誌。 控制台顏色 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 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 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 $vbLabelText $csharpLabel 改變控制台文字顏色可以突出特定輸出,使不同類型的信息更容易區分。 IronPrint:為 .NET 開發人員提供進階列印功能 IronPrint是由 Iron Software 開發的一款功能強大的列印庫。 IronPrint 是一個功能全面的列印庫,旨在與 .NET 應用程式無縫整合。 IronPrint 是一個可靠且功能豐富的 .NET 開發人員列印庫。 它具有跨平台相容性、支援多種文件格式以及可自訂設置,使其成為處理各種列印任務的寶貴工具。 無論您是開發桌面應用程式、行動應用程式還是 Web 應用程序,IronPrint 都能提供多功能的解決方案,以滿足您在不斷發展的 .NET 開發環境中的列印需求。 C# 列印變數(開發者如何理解):圖 3 - IronPrint 它提供了一系列功能,使開發人員能夠處理各種列印需求,從基本文件列印到可自訂設定和跨平台相容性。 主要功能 1.格式支援: IronPrint 支援多種文件格式,包括 PDF、PNG、HTML、TIFF、GIF、JPEG 和點陣圖。這種多功能性確保開發人員可以處理不同類型的列印內容。 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 套件管理器快速安裝該程式庫。 Install-Package IronPrint 或者,可以直接從 IronPrint NuGet 官方網站下載軟體包,或使用 NuGet 解決方案套件管理器下載。 應用許可證密鑰 在使用 IronPrint 功能之前,開發人員需要套用有效的授權或試用金鑰。 這涉及到將許可證密鑰分配給License類別的LicenseKey屬性。 以下程式碼片段示範了這一步驟: using IronPrint; // Apply license key License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01"; using IronPrint; // Apply license key License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01"; Imports IronPrint ' Apply license key License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01" $vbLabelText $csharpLabel 程式碼範例 列印文件 要使用 IronPrint列印文檔,開發人員只需將文件路徑傳遞給Print方法即可: using IronPrint; // Print the document Printer.Print("newDoc.pdf"); using IronPrint; // Print the document Printer.Print("newDoc.pdf"); Imports IronPrint ' Print the document Printer.Print("newDoc.pdf") $vbLabelText $csharpLabel 帶對話框的列印 在需要顯示列印對話方塊的情況下,可以使用ShowPrintDialog方法: using IronPrint; // Show print dialog Printer.ShowPrintDialog("newDoc.pdf"); using IronPrint; // Show print dialog Printer.ShowPrintDialog("newDoc.pdf"); Imports IronPrint ' Show print dialog Printer.ShowPrintDialog("newDoc.pdf") $vbLabelText $csharpLabel 自訂列印設定 若要以程式方式配置列印設置,開發人員可以實例化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); 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); Imports IronPrint ' Configure print settings Private printSettings As New PrintSettings() printSettings.Dpi = 150 printSettings.NumberOfCopies = 2 printSettings.PaperOrientation = PaperOrientation.Portrait ' Print the document with custom settings Printer.Print("newDoc.pdf", printSettings) $vbLabelText $csharpLabel 更多程式碼範例,請造訪此程式碼範例頁面。 結論 在 C# 中列印變數是每個開發人員都應該掌握的基本技能。 Console.WriteLine語句結合字串連接、字串字面量和字串插值等各種格式化技術,提供了一種靈活有效的方法來輸出變數值。 隨著你探索更複雜的場景,例如處理不同的資料類型和進階格式選項,你將增強在 C# 程式中有效傳達訊息的能力。 IronPrint 是一個付費庫,但開發者可以使用免費試用許可證來探索其功能。 更多信息,開發者可以訪問官方文檔和API 參考頁面。 從這裡下載庫檔案並試用一下。 常見問題解答 如何在 C# 中列印變數? 在 C# 中,使用 System 命名空間中的 Console.WriteLine 方法可以輕鬆完成變數的列印。這個方法允許您輸出變量值到控制台。例如Console.WriteLine($"Variable: {yourVariable}"); Console.Write 與 Console.WriteLine 在 C# 中有何差異? Console.Write 方法會將輸出寫入控制台,但不會在末尾加入換行符號,而 Console.WriteLine 則會附加換行符號,以確保後續輸出出現在新行上。 如何在 C# 中列印時格式化數字? 您可以在 C# 中使用格式指定符與字串插值來格式化數字。例如,若要列印有兩位小數的 double,請使用:Console.WriteLine($"{yourDouble:F2}"); 如何在 C# 中串聯字串和變數? 在 C# 中,可以使用 + 運算符連接字串和變數,或使用 $ 符號進行字串插值。例如Console.WriteLine("Total: 「 + totalCount); 或 Console.WriteLine($」Total: {totalCount}"); 。 什麼是 C# 中的逐字字串字面意義? C# 中的逐字字串字面意義以 @ 符號為前綴,用來處理帶轉義字元的字串,例如檔案路徑。它允許您以原樣寫入字串,而不需要轉換反斜線。 如何在 C# 中列印變數的資料類型? 若要在 C# 中列印變數的資料類型,請使用 GetType() 方法。例如Console.WriteLine($"Variable Type:{yourVariable.GetType()}");。 是否可以在 C# 中將控制台輸出重定向至檔案? 是的,透過使用 StreamWriter 類,您可以將控制台輸出重定向到檔案。為此,請設定 Console.SetOut(sw) ,其中 sw 是一個 StreamWriter 實例。 .NET 開發人員有哪些進階列印選項? .NET 開發人員的進階列印選項包括使用 IronPrint,這是一個支援各種文件格式和自訂列印設定的函式庫。它可以實現跨平台相容性,並在應用程式中有效率地處理列印任務。 如何處理 C# 字串文字中的轉義字元? C# 字串字面意義中的轉義字元可使用特定轉義序列的反斜線來管理,或使用帶有 @ 前綴的逐字字串字面意義來原封不動地使用字串。 有哪些工具可用於自訂 C# 的控制台輸出? 為了自訂控制台輸出,您可以使用 Console.ForegroundColor 和 Console.BackgroundColor 屬性來變更文字顏色,以強化資料的視覺呈現。 Jacob Mellor 立即與工程團隊聊天 首席技术官 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 技術的創新,同時指導新一代技術領袖。 相關文章 更新7月 28, 2025 C# 打印列表:快速教程 在這篇文章中,我們將探索在 C# 中打印列表的不同方法。 閱讀更多 更新7月 28, 2025 如何有效地使用 C# 打印行 在本文中,我們將探索與 C# 打印行有關的各種方法和技術。 閱讀更多 更新7月 28, 2025 精通 C# 打印函數:開發者指南 C# 打印的核心在於 Console.WriteLine 方法。這是顯示控制台上格式化輸出信息的首選函數 閱讀更多 如何有效地使用 C# 打印行精通 C# 打印函數:開發者指南