在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
在 C# 中打印變數是每位開發人員必備的技能。 無論您是在調試程式碼、向用戶顯示資訊,還是僅僅檢查程式的狀態,Console.WriteLine 語句都是進行標準輸出流操作時的首選工具。 來自命名空間 System 的Console類別提供Write和WriteLine方法,用於在控制台窗口上打印變量值。
在這篇全面的文章中,我們將探討C#中的變數列印的各個方面,包括不同的數據類型、格式選項和高級技術。
我們可以使用 Console.WriteLine 方法輕鬆列印數值,如以下程式碼範例所示。
int integerValue = 42; // specified value
Console.WriteLine($"Integer Value: {integerValue}"); // standard output stream
int integerValue = 42; // specified value
Console.WriteLine($"Integer Value: {integerValue}"); // standard output stream
Dim integerValue As Integer = 42 ' specified value
Console.WriteLine($"Integer Value: {integerValue}") ' standard output stream
在這個基本範例中,我們宣告了一個整數變數 (integerValue),並使用 Console.WriteLine 語句將指定的值列印到控制台。 $ 符號放在字串前面,允許我們使用字串插值將變數直接嵌入字串中。
string greeting = "Hello, C#!";
Console.WriteLine($"Greeting: {greeting}");
string greeting = "Hello, C#!";
Console.WriteLine($"Greeting: {greeting}");
Dim greeting As String = "Hello, C#!"
Console.WriteLine($"Greeting: {greeting}")
列印字符串變量遵循相同的模式。 我們宣告一個字串變數(greeting),指定一個字串值("Hello, C#!"),並使用 Console.WriteLine 來輸出。 這對於顯示訊息或任何文字信息非常有用。
如果您想在同一行打印變數的值,可以使用Console.Write方法。 這兩個方法之間唯一的區別是,WriteLine 在結尾留下了一個換行字符,因此下一個輸出將打印在下一行,而 Write 方法將所有內容打印在同一行。
int x = 5, y = 10;
Console.WriteLine($"X: {x}, Y: {y}");
int x = 5, y = 10;
Console.WriteLine($"X: {x}, Y: {y}");
Dim x As Integer = 5, y As Integer = 10
Console.WriteLine($"X: {x}, Y: {y}")
您可以在字串中用逗號分隔變數,來在單行内列印多個變數。 這有利於將相關資訊一起顯示。
double piValue = Math.PI;
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}");
double piValue = Math.PI;
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}");
Dim piValue As Double = Math.PI
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}")
格式化變得至關重要,尤其是對浮點數而言。 這裡,F5 格式規範確保 Pi 的值在小數點後面打印五位數字。
int apples = 3, oranges = 5;
Console.WriteLine("Total Fruits: " + (apples + oranges));
int apples = 3, oranges = 5;
Console.WriteLine("Total Fruits: " + (apples + oranges));
Dim apples As Integer = 3, oranges As Integer = 5
Console.WriteLine("Total Fruits: " & (apples + oranges))
字串連接可用於更複雜的輸出。 在這裡,水果的總數已計算並打印在同一行。
bool isTrue = true;
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}");
bool isTrue = true;
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}");
Dim isTrue As Boolean = True
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}")
有時,顯示不僅是變量的默認值,還有變量的類型是有益的。 GetType() 方法可以實現這一點。
int width = 10, height = 5;
string formattedOutput = String.Format("Dimensions: {0} x {1}", width, height); Console.WriteLine(formattedOutput);
int width = 10, height = 5;
string formattedOutput = String.Format("Dimensions: {0} x {1}", width, height); Console.WriteLine(formattedOutput);
Dim width As Integer = 10, height As Integer = 5
Dim formattedOutput As String = String.Format("Dimensions: {0} x {1}", width, height)
Console.WriteLine(formattedOutput)
String.Format 方法提供了另一種格式化字串和打印變數的方式,提供了對輸出結構的更大控制。
string filePath = @"C:\MyDocuments\file.txt";
Console.WriteLine($"File Path: {filePath}");
string filePath = @"C:\MyDocuments\file.txt";
Console.WriteLine($"File Path: {filePath}");
Dim filePath As String = "C:\MyDocuments\file.txt"
Console.WriteLine($"File Path: {filePath}")
對於包含轉義字符的路徑或字符串,可以使用逐字字符串字面值(以@為前綴)來簡化代碼。 在這裡,字串格式化有助於輕鬆打印文件路徑。
以下代碼示例幫助您將控制台窗口輸出寫入文件:
using System;
using System.IO;
class Program
{
// public static void Main
public static void Main(string [] args)
{
string outputPath = "output.txt";
using (StreamWriter sw = new StreamWriter(outputPath))
{
Console.SetOut(sw);
Console.WriteLine("This will be written to the file.");
}
}
}
using System;
using System.IO;
class Program
{
// public static void Main
public static void Main(string [] args)
{
string outputPath = "output.txt";
using (StreamWriter sw = new StreamWriter(outputPath))
{
Console.SetOut(sw);
Console.WriteLine("This will be written to the file.");
}
}
}
Imports System
Imports System.IO
Friend Class Program
' public static void Main
Public Shared Sub Main(ByVal args() As String)
Dim outputPath As String = "output.txt"
Using sw As New StreamWriter(outputPath)
Console.SetOut(sw)
Console.WriteLine("This will be written to the file.")
End Using
End Sub
End Class
將控制台輸出重定向到文件可讓您捕獲並保存輸出以便進一步分析或記錄目的。
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This text will be displayed in red.");
Console.ResetColor(); // Reset color to default
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This text will be displayed in red.");
Console.ResetColor(); // Reset color to default
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("This text will be displayed in red.")
Console.ResetColor() ' Reset color to default
更改控制台文本顏色可以為特定輸出添加視覺強調,讓區分不同類型的信息變得更容易。
IronPrint 是一個由 Iron Software 開發的強大印刷庫。 IronPrint 是一個全面的列印函式庫,旨在與 .NET 應用程式無縫整合。 IronPrint 是一個可靠且功能豐富的 .NET 開發人員打印庫。 其跨平台的相容性、對各種文件格式的支援以及可自定義的設定使其成為處理多樣印刷任務的寶貴工具。 無論您是為桌面、移動或網頁應用程式開發,IronPrint 都提供一個多功能的解決方案,以滿足您在不斷發展的 .NET 開發環境中的列印需求。
它提供了一系列功能,使開發人員能夠處理多種列印需求,從基礎文件列印到可自訂設定和跨平台相容性。
格式支援:IronPrint 支援多種文件格式,包括 PDF、PNG、HTML、TIFF、GIF、JPEG 和 BITMAP。這種多樣性確保開發人員可以使用不同類型的內容進行列印。
可自訂設定:開發人員可以根據應用程式的需求靈活自訂列印設定。 這包括設定 DPI(每英寸點數)、指定紙張方向(縱向或橫向)以及控制影印的份數。
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 setting
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 setting
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 setting
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 參考頁面。 從這裡下載庫並嘗試一下。