C# 列印變數:簡化您的程式碼
在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
在這個基礎範例中,我們宣告一個整數變數(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
列印字串變數遵循相同的模式。 我們宣告一個字串變數(greeting),賦予一個字串值("Hello, C#!"),並使用Console.WriteLine進行輸出。 這對於顯示訊息或任何文字資訊非常有用。

如果您想在同一行上列印變數值,您可以使用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
您可以在單行內通過用逗號將它們分隔來列印多個變數。 這對於一起顯示相關資訊的情況非常有利。

變數格式化
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
格式化至關重要,特別是對於浮點數來說。 在此,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
字串串連可以用於更複雜的輸出。 在這裡,水果的總數量被計算出來並在單行內列印。
列印變數型別
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
有時,顯示的不僅是變數的預設值,還包括變數的型別。 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
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
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
對於帶有轉義字元的路徑或字串,逐字字串常量(以@為前綴)可以簡化程式碼。 在此,字串格式化幫助我們輕鬆地列印文件路徑。
控制台輸出控制
重定向控制台輸出
以下程式碼範例可幫助您將控制台視窗輸出寫入文件:
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
將控制台輸出重定向到文件可以讓您捕獲並保存輸出以供進一步分析或記錄。
控制台顏色
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
更改控制台文字顏色為特定輸出增加了視覺上的強調,使分辨資訊的不同型別更加容易。
IronPrint: 為 .NET 開發者賦予進階列印功能
IronPrint是由Iron Software開發的一個強大的列印程式庫。 IronPrint 是一個綜合性的列印程式庫,旨在無縫整合於.NET應用程式中。 IronPrint 作為可靠且功能豐富的 .NET 開發者列印程式庫而存在。 其跨平台相容性、對各種文件格式的支持以及可自訂設置使其成為處理多樣列印任務的寶貴工具。 無論您是為桌面、移動或網頁應用程式開發,IronPrint 提供了一個多用途解決方案,以滿足您在不斷發展的.NET 開發領域中的列印需求。

它提供了一系列功能,使開發者能夠處理從基本文件列印到可自訂設置和跨平台相容的多樣列印需求。
主要特點
- 格式支持:IronPrint 支持多種文件格式,包括PDF、PNG、HTML、TIFF、GIF、JPEG和BITMAP。這種靈活性確保開發人員能夠處理不同型別的列印內容。
- 可自訂設置:開發者可以根據應用程式的需求自由自訂列印設置。 這包括設置DPI(每英寸點數)、指定紙張方向(縱向或橫向)和控制副本數量的選項。
- 列印對話框: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"
程式碼範例
列印文件
要使用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")
帶對話框列印
在需要列印對話框的情況下,可以使用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")
自訂列印設置
要以程式方式配置列印設置,開發者可以實例化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)
有關更多程式碼範例,請存取此程式碼範例頁面。
結論
在C#中列印變數是每位開發者應該掌握的基本技能。 Console.WriteLine語句結合各種格式化技術,如字串串連、字串常量和字串插值,提供了一種靈活且有效的方式來輸出變數值。 當您探索更複雜的情境,例如使用不同的資料型別和進階的格式化選項時,您將增強在C#程式中有效傳達資訊的能力。
IronPrint 是一個需要付費的程式庫,但開發者可以使用免費試用授權來探索其功能。 有關更多資訊,開發者可以存取官方文件和API參考頁面。 從這裡下載該程式庫並試用。
常見問題
我如何在C#中列印變數?
在C#中,列印變數可以藉由使用Console.WriteLine方法輕鬆地完成,這個方法來自System命名空間。該方法允許您將變數值輸出到控制台。例如:Console.WriteLine("Variable: {yourVariable}");
C#中的Console.Write和Console.WriteLine有什麼區別?
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屬性來增強資料的視覺呈現。




